TRT
Sign in
mediumCoreLeetCode#sorted half

Search in rotated sorted array

Find a target in a sorted array that has been rotated, in O(log n), by identifying the sorted half at each step.

The Runtime Theory Team1 min read
Taught inRotated and two-dimensional dataPro — members onlyBinary search still works when sorted data has been rotated, because one half of any range is always sorted. Sorted grids can be searched as one long array, or with a staircase walk from a corner.
Solve it

Solving happens on the judge — come back and mark it done

Sample cases

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

out4

innums = [4, 5, 6, 7, 0, 1, 2], target = 3

out-1

innums = [1], target = 0

out-1

A sorted array of distinct values was rotated at an unknown index. Given the rotated array and a target, return the target's index or -1, in O(log n).

Before you code

The array has one drop. Split any range in two and one half has no drop, so it is sorted, and a range check on that half is reliable.

Hints

  1. If a[lo] <= a[mid], the left half is sorted; otherwise the right half is.
  2. If the target lies within the sorted half's end values, search there; otherwise search the other half.
  3. Use a closed range consistently: while lo <= hi, hi = mid - 1, lo = mid + 1.

Production & complexity notes

When solving Search in rotated sorted array on LeetCode (medium), always state your loop or recursion invariant before writing code. Verify how your chosen data structure behaves on degenerate inputs (single-element inputs, all-duplicate keys, strictly monotonic sequences, or maximum constraint sizes up to $10^5$ elements). In production interviews, pair your implementation with an explicit time and auxiliary space complexity proof, explain why alternative brute-force approaches violate the latency budget, and trace how cache locality and memory allocation overhead affect wall-clock throughput on real hardware. Review the step-by-step memory trace in Rotated and two-dimensional data to reinforce the underlying pattern.

What it practices

Binary search on partly sorted data, from Rotated and two-dimensional data.

Not started

Sign in to save your learning progress.

Sign in to save