Search in Rotated Sorted Array

Difficulty: Medium

Take a sorted list of distinct numbers and move a chunk from the front to the back. For example, [0, 1, 2, 4, 5, 6, 7] becomes [4, 5, 6, 7, 0, 1, 2]. This is a "rotated" sorted list: it no longer starts at the smallest value.

Given a rotated list and a target, find the target's index, or report that it isn't there.

Examples

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

0 sits at index 4.

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

3 never appears anywhere in this particular rotated list.

Input: nums = [1], target = 0
Output: -1

The list has one element and it isn't the target.

Constraints

  • 1 <= nums.length <= 5000

  • -10^4 <= nums[i] <= 10^4

  • All values of nums are unique.

  • nums is an ascending list that has been rotated at some unknown pivot.

  • -10^4 <= target <= 10^4

Approach

Scanning every element works, but it ignores that the list is two sorted pieces, one moved to the end.

During binary search, look at the middle element. One half (left to middle, or middle to right) is always fully sorted. Compare its two endpoints to tell which.

Then check whether the target falls inside the sorted half's value range. If it does, search that half; if not, search the other one. Either way, half the list is dropped each round, like ordinary binary search.

Solutions

Brute Force — Linear Scan

Check every element until the target turns up. The rotation doesn't matter; a full scan finds it, just slowly.

function search(nums, target) {
  for (let i = 0; i < nums.length; i++) {
    if (nums[i] === target) return i;
  }
  return -1;
}

Time: O(n) · Space: O(1)

Optimal — Modified Binary Search

Run a binary search. At each step, find which half is sorted, then use its value range to decide whether the target could be in it.

function search(nums, target) {
  let left = 0;
  let right = nums.length - 1;

  while (left <= right) {
    const mid = Math.floor((left + right) / 2);

    if (nums[mid] === target) return mid;

    if (nums[left] <= nums[mid]) {
      // Left half is a normal sorted run.
      if (nums[left] <= target && target < nums[mid]) {
        right = mid - 1;
      } else {
        left = mid + 1;
      }
    } else {
      // Right half is a normal sorted run.
      if (nums[mid] < target && target <= nums[right]) {
        left = mid + 1;
      } else {
        right = mid - 1;
      }
    }
  }

  return -1;
}

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