Search in Rotated Sorted Array
Given a rotated sorted array and a target value Return the index of target, or -1 if not found Must run in O(log n) time Example: [4,5,6,7,0,1,2], target = 0 => 4 Example: [4,5,6,7,0,1,2], target = 3 => -1
An array of distinct integers was sorted in ascending order and then rotated at an unknown index, so [0,1,2,4,5,6,7] might become [4,5,6,7,0,1,2]. Given nums and a target, return the index of target, or -1 if it is absent. Part 2 returns the rotation index, the index of the smallest element, which is 0 when the array was not rotated. Part 3 allows duplicate values and asks only whether target is present, returning true or false.
Examples
You write
search(nums: List[int], target: int)
Example 1
- Input
- nums = [4,5,6,7,0,1,2], target = 0
- returns
- 4
Example 2
- Input
- nums = [4,5,6,7,0,1,2], target = 3
- returns
- -1
The pattern behind it
Arrays & Hashing
I reach for it when
- You catch yourself scanning the array again for every element.
- The problem asks about duplicates, pairs, counts or groups.
Say this before you type. Say what the key is and what the value remembers, before you write the loop.
All 127 Arrays & Hashing problemsBinary Search
I reach for it when
- The input is sorted, or sorted and then rotated.
- You want a boundary: the first or last place something is true.
Say this before you type. Say the yes-or-no question, and which side each answer throws away.
All 19 Binary Search problems
Meet Coco
Coco is an AI study partner, not a person. She listens while you explain your code, asks what a line does and never hands you the fix. Sign in free to type with Coco, up to a daily limit. The editor and Run stay open without an account. Anyone can open the editor and run their code.
Each locked part opens in the editor once the part before it passes.
Prep guides that list this problem
Our company tags come from public interview write-ups. None of these is a confirmed question.