A list of whole numbers was sorted from small to large, and values may repeat. Then it was rotated: some prefix was cut off and moved to the end, so [1, 2, 2, 5, 7] might become [5, 7, 1, 2, 2]. You get the rotated list nums and a number target.
Return true if target appears anywhere in nums, and false if it does not. Try to do fewer steps than reading the whole list.
Example 1
Input: nums = [5, 1, 5, 5, 5, 5, 5], target = 1 Output: true Why: the 1 sits at index 1
2 more examples and the constraints
Example 2
Input: nums = [4, 6, 7, 7, 0, 2, 4], target = 3 Output: false Why: 3 is not in the list
Example 3
Input: nums = [3, 1], target = 1 Output: true Why: rotated by one; 1 is the last value
Constraints
- 1 ≤ length of nums ≤ 5,000
- −10,000 ≤ each value, target ≤ 10,000
- nums is a sorted list rotated by some amount (possibly 0)
Your turn first
Have a go on paper or in your own editor, then reveal the approaches from the simplest up.
- Linear scanO(n)
- Binary search, skip equal endsO(log n) avg
The idea in one sentence
The pattern, how to spot it, and the best complexity.
Side by side
| Approach | Time | Values read for 5,000 numbers, few repeats | Verdict |
|---|---|---|---|
| Linear scan | O(n) | Correct; ignores the order | |
| Binary search, skip equal ends | O(log n) avg | Best; O(n) only with many repeats |
n = length of nums. With almost all values equal, both approaches read about n values.
Edge cases to test
- Equal ends and middle.
[5, 1, 5, 5, 5, 5, 5]: the first round cannot pick a half and must shrink both ends. - One value.
[8]with target 8 is true; with any other target it is false. - Not rotated. A plain sorted list is a rotation by 0 and must work as normal binary search.
- Target missing. The range empties out and the answer is false.
- All values equal.
[2, 2, 2, 2]reads every value before giving up on a target of 3.
Common mistakes
- Using the no-repeats test
nums[lo] <= nums[mid]alone, which picks the wrong half when the ends equal the middle. - Writing
target <= nums[mid]in the left half check, afternums[mid]was already ruled out. - Claiming O(log n) worst case. Repeats can force O(n).
How to talk through it
- 1Clarify. Can values repeat? Could the list be not rotated at all? Do I return a position or just true or false?
- 2Give the scan. A full scan is O(n) and always correct. Then use the near-sorted order.
- 3Explain the sorted half. One half of any cut is sorted; check if the target fits it, and keep or drop that half.
- 4Handle repeats. When both ends equal the middle, you cannot tell; shrink both ends by one. Say this makes the worst case O(n).
- 5Test out loud. Run the equal-ends case, a missing target, and a list that is not rotated.
Was this problem useful?Your vote tells us what to improve next.
Found a bug in our code, or something unclear?