InterviewPrepKit

Home / Coding / Binary Search

Search in Rotated Sorted Array

medium Original ↗
Solving tips
  • Key insight: no matter where you cut a rotated sorted array, at least one half is fully sorted; detect which by comparing nums[lo] with nums[mid] (use <= so a one-element half counts as sorted).
  • For the sorted half do an O(1) range check on the target's value; if it lies inside, recurse there, otherwise recurse into the other half, standard binary search invariant.
  • Target O(log n) time, O(1) space; get the half-open ranges right (nums[lo] <= target < nums[mid], nums[mid] < target <= nums[hi]) since mid is excluded by the equality check.
  • Pitfall: this exact code assumes distinct values, duplicates (Search in Rotated Sorted Array II) make nums[lo]==nums[mid]==nums[hi] ambiguous and degrade to O(n).

Problem

An ascending array of distinct integers was rotated at some unknown pivot: some suffix of the sorted array was moved to the front. For example, [0,1,2,4,5,6,7] rotated at index 3 becomes [4,5,6,7,0,1,2]. (The rotation may also be trivial — the array left as-is.)

Given the rotated array nums and a target, return the index of target in nums, or -1 if it is not present. Your algorithm must run in O(log n) time.

Examples

  • nums = [4,5,6,7,0,1,2], target = 04 0 sits at index 4, in the smaller “right half” of the rotation.
  • nums = [4,5,6,7,0,1,2], target = 3-1 3 is not in the array.
  • nums = [1], target = 10 A single-element array; the rotation is trivial.

Constraints

  • 1 <= len(nums) <= 5000
  • -10^4 <= nums[i], target <= 10^4
  • All values are distinct.
  • Required time: O(log n) — the constraint that rules out a linear scan.

Think about it first

Hint 1 Cut the rotated array anywhere. Can both halves be unsorted at the same time?
Hint 2 At least one half of any split is perfectly sorted, and you can tell which by comparing `nums[lo]` with `nums[mid]`. For a sorted half you can check in O(1) whether the target's value could be inside it.
Hint 3 Standard binary search, with one twist per iteration: identify the sorted half; if the target lies within that half's value range, recurse into it, otherwise recurse into the other half. (Alternatively: first binary-search for the pivot — the minimum — then run a normal binary search in whichever of the two sorted segments could contain the target.)
Your workspace Not runnable by design — this is your interview scratchpad. Saved on this device.