An interactive visualization of modified binary search on a rotated sorted array. Watch the algorithm determine which half is sorted and narrow down the search space step by step.
Binary Search LeetCode 33 ↗ Mediumnums sorted in ascending order (with distinct values),
which is possibly rotated at an unknown pivot index k.[0,1,2,4,5,6,7] might be rotated at pivot index 3 to become [4,5,6,7,0,1,2].nums after the possible rotation and an integer target,
return the index of target if it is in nums, or -1 if it is not.O(log n) runtime complexity.
fun search(nums: IntArray, target: Int): Int { var lo = 0; var hi = nums.size - 1 while (lo <= hi) { val mid = (lo + hi) / 2 if (nums[mid] == target) return mid if (nums[lo] <= nums[mid]) { // left half sorted if (nums[lo] <= target && target < nums[mid]) hi = mid - 1 else lo = mid + 1 } else { // right half sorted if (nums[mid] < target && target <= nums[hi]) lo = mid + 1 else hi = mid - 1 } } return -1}
In a rotated sorted array, when you split it at any midpoint, at least one half is always sorted. This is the crucial observation that lets us apply binary search even though the whole array is not sorted. We can check which half is sorted, determine if the target lies within that sorted half, and eliminate half the search space each step.
lo = 0, hi = len(nums) - 1mid = (lo + hi) // 2nums[mid] == target, return midnums[lo] <= nums[mid]): if target is in [nums[lo], nums[mid]), search left (hi = mid - 1); otherwise search right (lo = mid + 1)(nums[mid], nums[hi]], search right (lo = mid + 1); otherwise search left (hi = mid - 1)-1
Each iteration eliminates half of the remaining search space, giving us O(log n) time.
Only a constant number of variables are used regardless of input size.