You are given nums, an array of whole numbers that was sorted from small to large and then turned: some values were taken off the end and put back at the front, in order. It may have been turned all the way round, so it looks untouched. Unlike the simpler version of this problem, values may repeat.
Return the smallest value in nums, using as few steps as you can.
Example 1
Input: nums = [6, 7, 9, 2, 6, 6] Output: 2 Why: the values drop from 9 to 2
2 more examples and the constraints
Example 2
Input: nums = [5, 5, 5, 1, 5] Output: 1 Why: the 1 hides between equal values
Example 3
Input: nums = [3, 3, 3] Output: 3 Why: every value is the same
Constraints
- 1 ≤ length of nums ≤ 5,000
- −5,000 ≤ every value ≤ 5,000
- nums is a sorted array turned 1 to n times
Your turn first
Have a go on paper or in your own editor, then reveal the approaches from the simplest up.
- Scan every valueO(n)
- Binary search with a tie ruleO(log n) typical
The idea in one sentence
The pattern, how to spot it, and the best complexity.
Side by side
| Approach | Time | Relative work for 5,000 values with few repeats | Verdict |
|---|---|---|---|
| Scan every value | O(n) | Passes; ignores the order | |
| Binary search with a tie rule | O(log n), O(n) worst | Best; falls back to O(n) on ties |
n = the length of nums.
Edge cases to test
- All values equal. [3, 3, 3] ties on every step; hi walks down to lo and the answer is 3.
- Not turned at all. [1, 2, 2, 2]: nums[mid] never beats nums[hi], so hi slides to index 0.
- One value. [7]: the loop never runs and the answer is 7.
- Minimum hidden by ties. [10, 1, 10, 10, 10]: the first probe ties, and dropping hi is what lets the search find the 1.
Common mistakes
- Moving lo on a tie, which can skip the minimum when it sits right of mid.
- Comparing with nums[lo] instead of nums[hi]; an untouched array then sends the search the wrong way.
- Using
hi = mid − 1when mid is smaller, which can throw away the minimum itself.
How to talk through it
- 1Clarify. Can values repeat? Can the array be untouched? Is it ever empty?
- 2Give the scan. Reading every value is O(n) and always right; say so first.
- 3Recall the simpler version. Without repeats, compare mid with hi and halve the range each step.
- 4Handle the tie. Equal values give no direction, but hi has a twin at mid, so drop hi. That makes the worst case O(n).
- 5Test out loud. Run [5, 5, 5, 1, 5], [3, 3, 3] and [2, 1] by hand.
Was this problem useful?Your vote tells us what to improve next.
Found a bug in our code, or something unclear?