Solution: Binary Search
Let's solve the Binary Search problem using the Modified Binary Search pattern.
We'll cover the following
Statement
We are given an array of integers, nums
, sorted in ascending order, and an integer value, target
. If the target
exists in the array, return its index. If the target
does not exist, return -1
.
Constraints:
nums.length
nums[i]
,target
All integers in
nums
are unique.nums
is sorted in ascending order.
Solution
Binary search locates a target value in a sorted array by repeatedly dividing the search space in half. We compare the target with the middle element, starting with the entire array. If they match, we return the index. If the target is smaller, we narrow the search to the left half; if larger, we search the right half. This process continues until the target is found or the search space is exhausted.
We can solve the above problem using the iterative approach by following the steps below:
Initialize
low
to 0 andhigh
tonums.length - 1
.While
low
is less than or equal tohigh
:Compute
mid
using the formulaIf
nums[mid]
is equal to the target, returnmid
.If
nums[mid]
is greater than the target, updatehigh = mid - 1
to search in the left half.If
nums[mid]
is less than the target, updatelow = mid + 1
to search in the right half.
Repeat the process by recalculating
mid
in each iteration.
If
low
becomes greater thanhigh
, return-1
, indicating that the target is not in the array because the algorithm has checked all the positions where the target could be.
Let’s look at the following illustration to get a better understanding of the algorithm:
Level up your interview prep. Join Educative to access 70+ hands-on prep courses.