Search a rotated list
medium
New here? How this page works
- Read the Problem tab. Read it twice. Look at the examples: what goes in, what should come out.
- Open Break it down. Answer the questions in your own words. This is your plan.
- Write code on the right. Start small. Stuck on a blank page? Press “Write my plan as comments”.
- Press Run examples. See which examples pass. Red ones show what your code gave and what was expected.
- Stuck? Use Hints, one at a time. Still stuck after all of them? Read the Walkthrough. That's learning, not cheating.
- Press Submit. It runs hidden tests too. Pass them all, and it's solved.
A sorted list of different numbers was cut at some point, and the two pieces were swapped. For example, [1, 2, 4, 5, 6, 7, 9] cut after the 5 becomes [6, 7, 9, 1, 2, 4, 5]. It might also not have been cut at all.
Given the result, nums, return the position of target, or -1 if it isn't there.
Examples
Example 1
- Input
- nums = [6, 7, 9, 1, 2, 4, 5], target = 2
- Output
- 4
2 is at position 4.
Example 2
- Input
- nums = [6, 7, 9, 1, 2, 4, 5], target = 8
- Output
- -1
Example 3
- Input
- nums = [1, 3, 5], target = 5
- Output
- 2
This list wasn't cut at all.
Rules
numshas between 0 and 1,000,000 different numbers.- Aim for O(log n): binary search, adapted.
Words on this page, in plain English (4)Open if any word is new to you
- Array (list)
- A list of values kept in order, inside square brackets. Like a row of numbered lockers.
- Index (position)
- Where an item sits in a list. Counting starts at 0, not 1, so the first item is at position 0.
- O(log n): logarithmic time
- The work grows very slowly, because each step throws away half. A million items need only about 20 steps.
- Sorted
- In order, smallest to biggest (or A to Z). Many fast tricks only work on sorted lists.
Answer each question in your own words before you look at ours. Rough notes are fine: the point is to think before you type code. Your answers stay in this browser.
1.What goes in?
Name every input and what it looks like. Can it be empty? Sorted? Negative?
Stuck? Each hint gives a little more away. Try the problem again after each one.
This explains the whole solution.
You will learn the most by trying first, even if you don’t finish. But if this pattern is new to you, reading the walkthrough first is a fine way to learn it.
1. Understand the problem
The list was sorted, then cut once and its pieces swapped: [6, 7, 9, 1, 2, 4, 5]. It's two sorted runs stuck together, with a drop where the cut was (9 then 1). Normal binary search breaks: the middle item no longer tells you which side everything else is on.
2. Solve an example by hand
Look for 2 in [6, 7, 9, 1, 2, 4, 5]. The middle is position 3, value 1. Not it. Now look at the left half, 6, 7, 9, 1: it starts at 6 and ends at 1, so it contains the drop. The right half, 1, 2, 4, 5, starts small and ends big: it's properly sorted. Is 2 between 1 and 5? Yes, so it must be in the right half. Search there: found at position 4.
3. The slow way
Check every item: O(n). With a million items, that ignores everything we know about the order.
4. Spot the pattern
Still mostly sorted, still looking something up: binary search. The new idea: when you split a rotated list in the middle, at least one half is sorted, because the drop can only be in one of them. And in a sorted half, we can check instantly whether the target could be there: is it between that half's first and last values?
5. The idea
At each step:
- Check the middle. Found? Done.
- Work out which half is sorted: if
nums[low] <= nums[mid], it's the left half; otherwise the right. - If the target is within the sorted half's range, search that half. Otherwise, search the other one.
One half is always sorted
nums
- target =
- 2
- sorted half =
- –
function rotatedSearch(nums, target) { let low = 0; let high = nums.length - 1; while (low <= high) { const mid = Math.floor((low + high) / 2); if (nums[mid] === target) { return mid; } if (nums[low] <= nums[mid]) { // The left half, low to mid, is sorted. if (nums[low] <= target && target < nums[mid]) { high = mid - 1; // target is in the left half } else { low = mid + 1; } } else { // The right half, mid to high, is sorted. if (nums[mid] < target && target <= nums[high]) { low = mid + 1; // target is in the right half } else { high = mid - 1; } } } return -1;}Search the whole list for 2.
6. The code, line by line
let low = 0; let high = nums.length - 1; while (low <= high) { const mid = Math.floor((low + high) / 2); if (nums[mid] === target) { return mid; }Normal binary search so far: a range, a middle, and a check for a match.
if (nums[low] <= nums[mid]) { // The left half, low to mid, is sorted. if (nums[low] <= target && target < nums[mid]) { high = mid - 1; // target is in the left half } else { low = mid + 1; }If the first item of the range is no bigger than the middle, there's no drop on the left: the left half is sorted. If the target is between
nums[low]andnums[mid], it's there; otherwise it must be on the right.} else { // The right half, mid to high, is sorted. if (nums[mid] < target && target <= nums[high]) { low = mid + 1; // target is in the right half } else { high = mid - 1; } }Otherwise the drop is on the left, so the right half is sorted. Same check, mirrored.
return -1;The range ran out.
The comparisons use < on the side of mid, because we already know nums[mid] isn't the target.
7. How fast is it?
| One by one | Adapted binary search | |
|---|---|---|
| Time | O(n) | O(log n) |
| Extra memory | O(1) | O(1) |
Common mistakes
nums[low] < nums[mid]instead of<=. When the range has 2 items,lowandmidare the same position. That half (one item) counts as sorted.- Checking whether the target is in the unsorted half. Its first and last values tell you nothing, because of the drop. Always reason about the sorted half.
Memorise the solution, once you understand it.
This shows the full solution, then helps you rebuild it from memory in four steps. Remembering it is what lets you write it again in an interview, or in a week. Your result goes into your reviews, so it comes back just before you'd forget.
Learn it by heart: Search a rotated list
Read the 24 lines slowly. For each one, say out loud what it does and why it is there. Then cover it and move on to step 2.
function rotatedSearch(nums, target) { let low = 0; let high = nums.length - 1; while (low <= high) { const mid = Math.floor((low + high) / 2); if (nums[mid] === target) { return mid; } if (nums[low] <= nums[mid]) { // The left half, low to mid, is sorted. if (nums[low] <= target && target < nums[mid]) { high = mid - 1; // target is in the left half } else { low = mid + 1; } } else { // The right half, mid to high, is sorted. if (nums[mid] < target && target <= nums[high]) { low = mid + 1; // target is in the right half } else { high = mid - 1; } } } return -1;}