Skip to main content
Back to problems
Leetcode
Medium
Arrays
Binary Search
Divide and Conquer
Google
Search in Rotated Sorted Array

Find the index of a target value in a sorted array that has been rotated at an unknown pivot.

Acceptance 58%
Problem Statement

Problem

You are given a list of distinct integers that was originally sorted in ascending order, then rotated at an unknown pivot. For example, a sorted array like [0,1,2,4,5,6,7] may become [4,5,6,7,0,1,2].

Given the rotated array and a target value, return the index of the target if it exists. Otherwise, return -1.

You should aim for a solution that is faster than linear search.

Clarifications

  • All numbers are distinct.
  • The rotation may be zero, meaning the array may already be sorted.
  • If the target appears, return any valid index (there will be at most one because values are distinct).

Input Format

  • nums: an integer array of distinct values
  • target: an integer value to search for

Output Format

  • Return the index of target in nums, or -1 if it does not exist.

Constraints

  • 1 <= nums.length
  • Values in nums are distinct
  • nums is sorted in ascending order and then rotated
  • A logarithmic-time approach is expected
Examples
Sample cases returned by the problem API.

Example 1

Input

nums = [4,5,6,7,0,1,2], target = 0

Output

4

Explanation

The value 0 is present at index 4.

Example 2

Input

nums = [4,5,6,7,0,1,2], target = 3

Output

-1

Explanation

The value 3 does not appear in the array.

Show 1 more example

Example 3

Input

nums = [1], target = 1

Output

0

Explanation

The only element matches the target.

Premium problem context

Unlock deeper context for this problem

Premium adds guided hints, editorial links, similar variants, discussion resources, and concept maps so you can understand why a problem matters, not just solve it once.

Guided hints
Editorial and discussion links
Concept map and variants
Sign in to unlock
Track your progress
Sign in to bookmark this problem, save notes, and manage its revision plan.