Binary Search · Easy

Binary Search

O(log N) · O(1)

Initialize Binary Search Bounds

Array is sorted. Set Low = 0 (val -1) and High = 5 (val 12). Target = 9.

Array Elements & Pointers
Low
-1
[0]
0
[1]
3
[2]
5
[3]
9
[4]
High
12
[5]
Live Variables & Invariants
target:9
low:0
high:5
Step 1 / 5
20%
Solution Code
1
function search(nums: number[], target: number): number {
2
  let low = 0, high = nums.length - 1;
3
  while (low <= high) {
4
    const mid = Math.floor((low + high) / 2);
5
    if (nums[mid] === target) return mid;
6
    if (nums[mid] < target) low = mid + 1;
7
    else high = mid - 1;
8
  }
9
  return -1;
10
}
LeetCode IDE Console

Test Cases

4 cases from Blind 75 & NeetCode 150

Ask for a hint whenever you get stuck.