CodingEasy Searching & Stacks
Binary Search
Asked for all developer roles
Why they ask this: A fundamental algorithm; off-by-one errors in the loop are exactly what interviewers look for.
Problem
Given a sorted (ascending) array of distinct integers nums and a target, return the index of target, or -1 if it is not present. Your solution must run in O(log n) time.
Example 1
text
Input: nums = [-1, 0, 3, 5, 9, 12], target = 9
Output: 4Example 2
text
Input: nums = [-1, 0, 3, 5, 9, 12], target = 2
Output: -1Hints
Approach
Keep a search range [low, high], starting with the whole array. While low <= high:
mid = low + floor((high - low) / 2). Writing it this way avoids integer overflow in languages with fixed-size integers.- If
nums[mid] === target, returnmid. - If
nums[mid] < target, the target can only be to the right:low = mid + 1. - Otherwise it can only be to the left:
high = mid - 1.
If the loop ends, return -1. Each step halves the range, which gives O(log n).
Solution
js
function binarySearch(nums, target) {
let low = 0;
let high = nums.length - 1;
while (low <= high) {
const mid = low + Math.floor((high - low) / 2);
if (nums[mid] === target) return mid;
if (nums[mid] < target) low = mid + 1;
else high = mid - 1;
}
return -1;
}
console.log(binarySearch([-1, 0, 3, 5, 9, 12], 9)); // 4
console.log(binarySearch([-1, 0, 3, 5, 9, 12], 2)); // -1 Time
O(log n) Space O(1)Can you explain this in your own words?