Search in Rotated Sorted Array

35 min · search()

The sorted array has a bend in it. Your search needs to see around that corner.

You're given a strictly increasing array that was rotated, meaning a prefix — a block from the front — may have been moved to the end while both pieces kept their internal order. Given target, return its zero-based index, or -1 when it isn't present.

The array may have been rotated zero times, so ordinary sorted input is valid too.

A few ground rules:

  • All values are distinct, so a present target has one index.
  • You need to search the rotated order as given; don't sort a copy.
  • Aim to discard half of the remaining indices after each comparison.

Constraints

  • 1 <= nums.length <= 100_000
  • -1_000_000_000 <= nums[i], target <= 1_000_000_000
  • All values are distinct.
  • nums is a rotation of a strictly increasing array.

Hints

One half is still clean

For any middle index, at least one side of the current interval is normally sorted. Compare nums[left], nums[middle], and nums[right] to identify it.

Ask whether target fits

Once you know which half is sorted, check whether target falls inside that half's value range. Keep that half if it does; discard it if it doesn't.

Use inclusive boundaries carefully

In the sorted left half, test nums[left] <= target < nums[middle]. The mirrored right-half test is nums[middle] < target <= nums[right].

Follow-up

How does the reasoning change when duplicate values can make both ends equal to the middle?

Visible cases

Examples

Example 1

ready
Input
nums = [
  4,
  5,
  6,
  7,
  0,
  1,
  2
]
target = 0
Expected
4
Why
0 is present in the low-value half

Example 2

ready
Input
nums = [
  4,
  5,
  6,
  7,
  0,
  1,
  2
]
target = 6
Expected
2
Why
6 is present before the rotation seam

Example 3

ready
Input
nums = [
  4,
  5,
  6,
  7,
  0,
  1,
  2
]
target = 3
Expected
-1
Why
3 doesn't appear on either side

Interview signal

Asked at

AmazonGoogleMicrosoft
Loading editor

Console

ready to run

Ready to run.

3 cases are queued.

Run: visible + custom · Submit: full suite