Search in Rotated Sorted Array

Task example: Search in Rotated Sorted Array

A non-empty array nums contains distinct integers in increasing order, possibly rotated. Given target, return its index, or -1 if it is absent. Keep nums unchanged. The required runtime is O(log n); the linear scan below is a baseline.

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

Target 0 is at index 4, so return 4. Target 3 is absent, so return -1. Values must be distinct; an unrotated array or a single element is also valid.

01 / Linear scan - baseline

Linear scan: video explanation

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

Prefer reading? Follow the steps below.

  1. Visit indices 0 through n - 1. At each index, compare nums[i] with target.
  2. When they match, return i immediately. For target 0 in [4,5,6,7,0,1,2], the first match is at index 4.
  3. Return -1 only after the entire loop finishes without a match. Putting this return inside the loop would stop after just one failed comparison.

Time complexity · O(n)

Worst-case time complexity is O(n): a missing target or a match at the last index requires n comparisons.

Space complexity · O(1)

Only the loop index is stored. No copied array is needed: O(1) extra space.

PYTHONLive code trace
02 / Binary search - optimal solution

Binary search: video explanation

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

Prefer reading? Follow the steps below.

  1. Set left = 0 and right = len(nums) - 1. While left <= right, calculate mid. If nums[mid] equals target, return mid immediately.
  2. If nums[left] <= nums[mid], the left half is sorted. Keep it only when nums[left] <= target < nums[mid]: set right = mid - 1. Otherwise set left = mid + 1.
  3. Otherwise the right half is sorted. If nums[mid] < target <= nums[right], set left = mid + 1; otherwise set right = mid - 1. The checked middle can be excluded.
  4. If left passes right, the target is absent: return -1. For target 0 in [4,5,6,7,0,1,2], mid visits indices 3, 5, and 4, where the match is found.

Unlike a linear scan, binary search discards a whole half at once. Distinct values guarantee that the sorted half can be identified. Do not sort the input: that would change the original indices.

Time complexity · O(log n)

Each unsuccessful iteration roughly halves the search range: O(log n) time.

Space complexity · O(1)

Only left, right, and mid are stored. No sorting, recursion, or copied array is needed: O(1) extra space.

PYTHONLive code trace

Rotated array search · The task

Close or press Esc to return to your place. The task button stays pinned while you explore the solutions.