You are given nums, an array of distinct whole numbers. It was sorted from small to large, then turned: some number of values were taken off the end and put back at the front, in order. It may also have been turned all the way round, so it looks untouched.
Return the smallest value in nums. Your solution has to run in O(log n) time.
Example 1
Input: nums = [15, 18, 22, 26, 3, 7, 11] Output: 3 Why: the values drop from 26 to 3
2 more examples and the constraints
Example 2
Input: nums = [8, 1, 3, 5] Output: 1 Why: only 8 was moved to the front
Example 3
Input: nums = [2, 4, 6, 9] Output: 2 Why: turned all the way round, so the first value is smallest
Constraints
- 1 ≤ length of nums ≤ 5,000
- Each number is between −5,000 and 5,000
- All the numbers are different
- nums is a sorted array turned between 1 and 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 against the right endO(log n)
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 numbers | Verdict |
|---|---|---|---|
| Scan every value | O(n) | Correct, misses the O(log n) rule | |
| Binary search against the right end | O(log n) | Best; about 13 looks |
n = how many numbers are in the array.
Edge cases to test
- Not turned (or turned n times). [2, 4, 6, 9]: the answer is the first value.
- One number. [7]: the loop never runs and 7 comes back.
- Two numbers. [2, 1] and [1, 2] both give 1.
- Minimum at the end. [2, 3, 4, 5, 1]: the drop is the very last step.
Common mistakes
- Comparing mid with the left end, which cannot tell an untouched array from a turned one.
- Writing
hi = mid - 1when nums[mid] is smaller, which can skip the minimum itself. - Using
while lo <= hiwithhi = mid, which loops forever once lo equals hi.
How to talk through it
- 1Clarify. Are all values distinct? Can the array be untouched? Is O(log n) required?
- 2Give the scan. A linear pass finds the minimum in O(n); say that it ignores the sorted order.
- 3Name the shape. Two rising runs; the minimum starts the second. The right end tells you which run mid is in.
- 4Code the search. Explain why it is
lo = mid + 1on one side andhi = midon the other. - 5Test out loud. Run an untouched array, a single value and a two-value array before saying you are done.
Was this problem useful?Your vote tells us what to improve next.
Found a bug in our code, or something unclear?