Skip to content
Work Practice Products Coding interviews Machine learning coding Quant developer HFT course Blog Method Why me About Enquire Book a call

Coding · Binary search

Find a value in a rotated sorted array

Medium · Target 20 minutes · Binary search · Type asked atMetaAmazonCitadelBloomberg

An array of distinct integers was sorted in increasing order and then rotated at an unknown point, so [0, 1, 2, 4, 5, 6, 7] might arrive as [4, 5, 6, 7, 0, 1, 2]. Given the rotated array and a target, return the index of target, or −1 if it is absent. Use O(log n) comparisons.

Examples

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

Constraints

  • 1 ≤ n ≤ 5000
  • −10⁴ ≤ nums[i], target ≤ 10⁴
  • All values are distinct

Hints

Hint 1

Comparing target with nums[mid] alone no longer tells you which side to keep. What else does the middle tell you?

Hint 2

The rotation point lies on at most one side of mid, so at least one of nums[lo..mid] and nums[mid..hi] is sorted. Compare nums[lo] with nums[mid] to see which.

Hint 3

For the sorted side you can test "is target between its ends?" exactly. If yes, search there; if no, search the other side.

Where people lose marks

  • Writing nums[lo] < nums[mid] instead of ≤: when lo = mid the left half is one element and is sorted.
  • Testing the unsorted half with a range check: its values are not the ones between its ends.
  • Mixing strict and non-strict bounds so that target = nums[mid] or target = nums[lo] falls through both tests.
Console⌘/Ctrl + Enter runs

Write a solution and run it against the real test table.


Keep going

Preparing for a real process? Quant interview preparation, or book a free 20-minute call.