MediumPythonJavaScriptTypeScript
Binary Search — Minimum in a Rotated Sorted Array
AlgorithmsBinary SearchArrays
solve(nums) — nums was sorted ascending with distinct values, then rotated an
unknown number of times ([0,1,2,4,5,6,7] can become [4,5,6,7,0,1,2]). Return the
smallest value in O(log n).
Compare nums[mid] to the last element, not the first: if nums[mid] > nums[hi]
the drop (and the minimum) is on the right of mid; otherwise the minimum is at mid
or on its left.
Examples
solve([3,4,5,1,2]) → 1
solve([4,5,6,7,0,1,2]) → 0
solve([11,13,15,17]) → 11 // rotated n times = not rotatedSample tests
Test #1Rotated array
Input: [[3,4,5,1,2]]
Output: 1
Test #2Classic example
Input: [[4,5,6,7,0,1,2]]
Output: 0
Test #3Not rotated
Input: [[11,13,15,17]]
Output: 11