#33

Search in Rotated Sorted Array

Medium Find the sorted half

  1. Read
  2. Understand
  3. Hints
  4. Approach
  5. Solution
  6. Solved

?The problem

A sorted array of distinct values was rotated at an unknown point. Find target's index in O(log n), or -1.

This is a short summary in our own words. Read the full statement and examples on LeetCode: open problem ↗

◎Understanding

Really asking: binary search in a sorted array that was rotated.

Why this works: at any mid, one half is still properly sorted. Check if the target lies in that half's range; otherwise search the other half.

Example: [4, 5, 6, 7, 0, 1, 2], target 0

mid 3 (7): left half 4..7 sorted, 0 not in it → go rightmid 5 (1): left half 0..1 sorted, 0 in it → go leftmid 4 (0) ✓

✦Hints open one at a time

↗Approach

</>Solution (Java)

!Common mistake

Using < instead of <= in nums[lo] <= nums[mid]; when lo == mid the left "half" is one element and is sorted.

Solve on LeetCode ↗
Complexity
  • Time: O(log n).
  • Space: O(1).
Topic: Binary Search
🎬 Episodes 21–23: video coming soon