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.lengthnums[i],targetAll integers in
numsare unique.numsis sorted in ascending order.
Solution#
The array provided is sorted, so whenever target is greater than any number in the array, target must be present in the subarray to the right of the number. Similarly, whenever target is less than any number in the array, target must be present in the subarray to the left of the number. We can solve the above problem using the iterative approach by following the steps below:
Let’s initialize the
lowandhighvariables toand nums.length-1, respectively.Calculate the
midindex using the formula. If
nums[mid]is equal to thetargetvalue, we returnmid.If
nums[mid]is greater thantarget, pointhightomid-1, and the value oflowremains the same. Now we will search the left part of the array.If
nums[mid]is less thantarget, pointlowtomid + 1, and the value ofhighremains the same. Now we will search the right part of the array.
When the value of
lowis greater than the value ofhigh, this indicates that thetargetis not present in the array. This is because we’ve checked all possible positions wheretargetmight exist. So,-1is returned.
Let’s look at the following illustration to get a better understanding of the algorithm:
1 of 7
2 of 7
3 of 7
4 of 7
5 of 7
6 of 7
7 of 7
Let’s see how the algorithm above is implemented.
Binary Search
First Bad Version