CodingNodes / Binary Search / Search In Rotated Sorted Array System design Space play · ←→ step · R restart

Problem

A list of distinct numbers was sorted in increasing order, then rotated: some items from the front were moved to the back, keeping their order.

Given the rotated list nums and a number target, return the index where target sits, or -1 if it is not there. Your solution must run in O(log n) time.

Constraints

  • 1 ≤ nums.length ≤ 5000
  • All values in nums are distinct
  • nums is a sorted list rotated between 0 and n times

Examples: pick one to animate

Solutions

TimeO(log n) SpaceO(1)

Time: Each round discards half of the range, so about log2(n) rounds.

Space: Only lo, hi and mid are stored.

At any mid, at least one side is sorted. If nums[lo] ≤ nums[mid] the left side is in order, otherwise the right side is. Check whether the target fits inside the sorted side. If yes, keep that side. If not, drop it and search the other.