Given a sorted array of n
integers and a target value, write a function to search for the target in the array. If the target exists, then return its index. Otherwise, return -1
.
You must write an algorithm with O(log n)
runtime complexity.
Input: nums = [-1,0,3,5,9,12], target = 9
Output: 4
Explanation: 9 exists in nums and its index is 4
Input: nums = [-1,0,3,5,9,12], target = 2
Output: -1
Explanation: 2 does not exist in nums so return -1
To achieve the required O(log n)
runtime complexity, the solution should use the binary search algorithm. Binary search works as follows:
left
starting at index 0
and right
starting at the last index of the array.mid
index.mid
index with the target.
mid
is the target, return mid
.mid
, adjust the right
pointer to mid - 1
.mid
, adjust the left
pointer to mid + 1
.left
exceeds right
.Here is the Python implementation of the binary search algorithm:
def search(nums, target):
left, right = 0, len(nums) - 1
while left <= right:
mid = left + (right - left) // 2
if nums[mid] == target:
return mid
elif nums[mid] < target:
left = mid + 1
else:
right = mid - 1
return -1
The time complexity of the binary search algorithm is O(log n)
, as each iteration of the loop halves the search space. This meets the problem’s requirement for an efficient search.
Let’s go through the example nums = [-1,0,3,5,9,12], target = 9
:
left=0
, right=5
(last index), mid = 2
(nums[2] = 3
), target = 9
.3 < 9
, update left = 3
.left=3
, right=5
, mid = 4
(nums[4] = 9
).9
matches the target
, so return 4
.With this approach, the function successfully returns the index of the target value if it exists, or -1
if it doesn’t.
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?