You are given an integer array nums
sorted in ascending order (with distinct values), and an integer target
. Suppose nums
is rotated at some pivot unknown to you beforehand (i.e., [0,1,2,4,5,6,7]
might become [4,5,6,7,0,1,2]
). You must search for target
in nums
and if you find it, return its index. Otherwise, return -1
.
You must write an algorithm with O(log n)
runtime complexity.
Example 1:
Input: nums = [4,5,6,7,0,1,2], target = 0
Output: 4
Example 2:
Input: nums = [4,5,6,7,0,1,2], target = 3
Output: -1
Example 3:
Input: nums = [1], target = 0
Output: -1
-1
.We can leverage a modified binary search to achieve the desired O(log n) runtime. Here’s a step-by-step breakdown of the approach:
low
) at the beginning of the array and end (high
) at the end of the array.nums[low] <= nums[mid]
):
nums[low] <= target < nums[mid]
). If so, move the high pointer to mid - 1
.mid + 1
.nums[mid] <= nums[high]
):
nums[mid] < target <= nums[high]
). If so, move the low pointer to mid + 1
.mid - 1
.def search(nums, target):
low, high = 0, nums.length - 1
while low <= high:
mid = (low + high) // 2
if nums[mid] == target:
return mid
# Left half is sorted
if nums[low] <= nums[mid]:
if nums[low] <= target < nums[mid]:
high = mid - 1
else:
low = mid + 1
# Right half is sorted
else:
if nums[mid] < target <= nums[high]:
low = mid + 1
else:
high = mid - 1
return -1
The time complexity of this algorithm is ( O(\log n) ) because it uses binary search, continuously dividing the search range by half.
The space complexity is ( O(1) ) because it only uses a constant amount of additional space for the pointers and the mid index.
Got blindsided by a question you didn’t expect?
Spend too much time studying?
Or simply don’t have the time to go over all 3000 questions?