Skip to problem
←

Search in Rotated Sorted Array

Medium 0 attempts

Given an array nums formed by rotating a strictly increasing array and an integer target, return the target's zero-based index in the given array, or -1 if it is absent.

All values are distinct. A rotation moves a prefix to the end without changing the order inside either part: [0, 1, 2, 4, 5, 6, 7] can become [4, 5, 6, 7, 0, 1, 2]. An unrotated array is also valid.

Use logarithmic time. For the rotated example above, target 0 has index 4; do not return its position in the originally sorted array or sort the array before searching.

Function contract

Implement search(nums, target).

Output: Return the zero-based index of target in the given rotated array, or -1 if absent.

Example 1

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

Example 2

Input
nums = [4,5,6,7,0,1,2]
target = 3
Output
-1
Constraints
  • 1 <= nums.length <= 5000
  • -10^4 <= nums[i] <= 10^4
  • All values are unique
  • nums is a rotation (possibly by zero positions) of a strictly increasing array.
  • -10^4 <= target <= 10^4

Binary Search on the Sorted Half

Check the midpoint first. If it does not match, at least one side of the current interval is sorted because there is at most one rotation break.

When nums[lo] <= nums[mid], the left half is sorted. Keep it only if nums[lo] <= target < nums[mid]; otherwise search the right half. If the left half is not sorted, the right half must be, so keep it only if nums[mid] < target <= nums[hi].

The midpoint is excluded after checking it, ensuring progress even for one- and two-element intervals. Each iteration discards at least half the candidates. Distinct values make the sorted-half test unambiguous; duplicate-valued inputs would require different handling.

javascript
function search(nums, target) {
  let lo = 0,
    hi = nums.length - 1;
  while (lo <= hi) {
    const mid = (lo + hi) >> 1;
    if (nums[mid] === target) return mid;
    if (nums[lo] <= nums[mid]) {
      if (target >= nums[lo] && target < nums[mid]) hi = mid - 1;
      else lo = mid + 1;
    } else {
      if (target > nums[mid] && target <= nums[hi]) lo = mid + 1;
      else hi = mid - 1;
    }
  }
  return -1;
}

Time: O(log n) | Space: O(1)

Loading discussion…

Saved in this browser only. Private to you.

JavaScript