Problem Description
Given an array of integers nums which is sorted in ascending order, and an integer target, write a function to search target in nums. If target exists, then return its index. Otherwise, return -1.
You must write an algorithm with O(log n) runtime complexity.
Example 1:
- Input:
nums = [-1,0,3,5,9,12], target = 9 - Output: 4
Example 2:
- Input:
nums = [-1,0,3,5,9,12], target = 2 - Output:
-1
My Idea
The idea here is to implement the basic version of binary search, where we compare with the middle element and depending on weather it’s value is > or < than our target we restrict our problem space to the left or right half of the array respectively. Thus halving the searched area with every step and yielding a time complexity of O(log n).
My solution
# Time complexity: O(log n)
def search(nums:list[int], target:int) -> int:
l=0
r=len(nums)-1
while l<=r:
mid = (l+r)//2
if nums[mid]>target:
r=mid-1
elif nums[mid]<target:
l=mid+1
else:
return mid
return -1