Binary Search
Explore how to apply binary search to find a target integer in a sorted array while handling constraints effectively. Learn to implement solutions that return the target index or -1 if absent, building foundational skills for coding interviews.
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.
Example
Understand the problem
Let’s take a moment to make sure you’ve correctly understood the problem. The quiz below helps you check if you’re solving the correct problem:
Binary Search
Find the index of the number 60 from the following array using binary search.
array = [-10, 11, 60, 70]
Also, calculate the number of comparisons required to find the number.
index: 0, steps: 2
index: 1, steps: 1
index: 2, steps: 2
index: 2, steps: 3
Figure it out!
We have a game for you to play. Rearrange the logical building blocks to develop a clearer understanding of how to solve this problem.
Try it yourself
Implement your solution in the following coding playground.
#include <vector>int BinarySearch(vector<int>& nums, int target){// Replace this placeholder return statement with your codereturn -1;}