Search in Rotated Sorted Array

MediumBinary Search · Rotated Array🧩 Binary SearchLeetCode #33 ↗Updated

Problem

An ascending array of distinct integers was possibly rotated at an unknown index (e.g. [0,1,2,4,5,6,7] → [4,5,6,7,0,1,2]). Given the rotated array nums and a target, return the index of target, or -1 if it is missing, in O(log n) time.
Input[4,5,6,7,0,1,2], t=0Output4
Input[4,5,6,7,0,1,2], t=3Output-1
Input[1], t=0Output-1

1 ≤ n ≤ 5000  ·  -104 ≤ nums[i], target ≤ 104  ·  all values distinct  ·  Required: O(log n).

Try it yourself

Java
class Solution {
    public int search(int[] nums, int target) {
        
    }
}
Your code is saved in this browser.Submit on LeetCode ↗
Key insight
Split a rotated array at any mid and at least one half is normally sorted. A range check on that sorted half tells you for certain whether the target can be there — otherwise discard it.
PatternBinary Search

Instinct Sorted data, a rotated array, or find the min/max X that works where a yes/no test flips only once - halve the search space every step.

Memory hack Find the fence - every candidate reads NO NO NO YES YES, and binary search just walks to where the fence stands.

Open the Binary Search guide →

Approaches

Brute ForceLinear Search

Time O(n)Space O(1)

Check every element until one equals target. Works on any array, rotated or not, because it never relies on order.

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

Correct and simple, but ignores the structure and misses the O(log n) bar.

At a glance

LevelApproachTimeSpace
Brute ForceLinear SearchO(n)O(1)
BetterFind Pivot, then Binary SearchO(log n)O(1)
OptimalOne-Pass Modified Binary SearchO(log n)O(1)
Common pitfalls
  • Using nums[left] < nums[mid] — fails when left == mid (2-element window).
  • Mixing strict and non-strict bounds in the range check — misses targets at the edges.
  • Pivot version: forgetting the un-rotated case (pivot = 0, left run is empty).
Interview tips
  • Draw the array as two ascending “ramps” to show one half is always sorted.
  • Mention the pivot approach first, then fold it into one pass.
  • Test: not rotated, rotated by n-1, single element, target at the pivot.
Pattern
Binary search on a partially sorted array → find which side is ordered, then decide by range check.
My notes saved in this browser