Binary Search
đź’» Try it yourself first. Write your solution in Java, C++, Python or JavaScript and run it against hidden tests, right here.On this page
Revision notes
Binary Search
Video: “Binary Search: cut the shelf in half” on LearnWithKiriti (Kodee). LeetCode 704.
Find the index of target in a sorted array of distinct numbers, or return -1.
Example: [2, 5, 8, 12, 16, 23, 38, 56], target 23 -> 5
| Folder | Approach | Time | Extra space |
|---|---|---|---|
Brute-LinearSearch/ |
Linear search: Linear search: check every number from the left. It ignores the one thing we were given: the array is sorted. | O(n) | O(1) |
Optimal-BinarySearch/ |
Binary search: Look at the middle (mid). If target is bigger, it can only be right of mid (low = mid + 1); if smaller, left of it (high = mid - 1). Half the shelf is gone every step. | O(log n) | O(1) |
Rebuild it
Sorted means one look rules out half. Compare the target with the middle (mid). Bigger: it can only be right of mid, so low = mid + 1. Smaller: high = mid - 1. Stop when low > high. Write mid = low + (high - low) / 2 so low + high never overflows.
See each folder’s pseudocode.md. Every program runs Example 1 and prints the answer; the same code is in the practice panel’s Start menu on learnwithkiriti.com, where Shelf Bot can act it out.
Brute: Linear Search
Brute: linear search
Linear search: check every number from the left. It ignores the one thing we were given: the array is sorted.
for scan from 0 to size - 1:
if nums[scan] == target:
return scan
return -1
O(n): a million books, up to a million looks. It never uses the fact that the shelf is sorted.
import java.util.*;
public class BinarySearchBrute {
public int search(int[] nums, int target) {
for (int scan = 0; scan < nums.length; scan++) {
if (nums[scan] == target) {
return scan;
}
}
return -1;
}
public static void main(String[] args) {
BinarySearchBrute solver = new BinarySearchBrute();
int[] nums = new int[]{2, 5, 8, 12, 16, 23, 38, 56};
int target = 23;
int answer = solver.search(nums, target);
System.out.println(answer);
}
}#include <bits/stdc++.h>
using namespace std;
class Solution {
public:
int search(vector<int>& nums, int target) {
for (int scan = 0; scan < (int) nums.size(); scan++) {
if (nums[scan] == target) {
return scan;
}
}
return -1;
}
};
void print(const vector<int>& values) {
cout << "[";
for (size_t spot = 0; spot < values.size(); spot++) {
if (spot > 0) {
cout << ", ";
}
cout << values[spot];
}
cout << "]" << endl;
}
void print(const vector<vector<int>>& grid) {
for (const vector<int>& line : grid) {
print(line);
}
}
int main() {
Solution solver;
vector<int> nums = {2, 5, 8, 12, 16, 23, 38, 56};
int target = 23;
cout << solver.search(nums, target) << endl;
return 0;
}def search(nums, target):
for scan in range(len(nums)):
if nums[scan] == target:
return scan
return -1
if __name__ == "__main__":
nums = [2, 5, 8, 12, 16, 23, 38, 56]
target = 23
print(search(nums, target))function search(nums, target) {
for (let scan = 0; scan < nums.length; scan++) {
if (nums[scan] === target) {
return scan;
}
}
return -1;
}
const nums = [2, 5, 8, 12, 16, 23, 38, 56];
const target = 23;
console.log(search(nums, target));Optimal: Binary Search
Optimal: binary search
Look at the middle (mid). If target is bigger, it can only be right of mid (low = mid + 1); if smaller, left of it (high = mid - 1). Half the shelf is gone every step.
low = 0
high = size - 1
while low <= high:
mid = low + (high - low) / 2
if nums[mid] == target: return mid
if target > nums[mid]: low = mid + 1
else: high = mid - 1
return -1
Dry run on Example 1:
Target 23 in [2, 5, 8, 12, 16, 23, 38, 56]:
| low | high | mid | nums[mid] | move |
|---|---|---|---|---|
| 0 | 7 | 3 | 12 | 23 > 12: low = 4 |
| 4 | 7 | 5 | 23 | found: 5 |
O(log n): a million books need at most 20 looks. O(1) extra space.
import java.util.*;
public class BinarySearchOptimal {
public int search(int[] nums, int target) {
int low = 0;
int high = nums.length - 1;
while (low <= high) {
int mid = low + (high - low) / 2;
if (nums[mid] == target) {
return mid;
}
if (target > nums[mid]) {
low = mid + 1;
} else {
high = mid - 1;
}
}
return -1;
}
public static void main(String[] args) {
BinarySearchOptimal solver = new BinarySearchOptimal();
int[] nums = new int[]{2, 5, 8, 12, 16, 23, 38, 56};
int target = 23;
int answer = solver.search(nums, target);
System.out.println(answer);
}
}#include <bits/stdc++.h>
using namespace std;
class Solution {
public:
int search(vector<int>& nums, int target) {
int low = 0;
int high = nums.size() - 1;
while (low <= high) {
int mid = low + (high - low) / 2;
if (nums[mid] == target) {
return mid;
}
if (target > nums[mid]) {
low = mid + 1;
} else {
high = mid - 1;
}
}
return -1;
}
};
void print(const vector<int>& values) {
cout << "[";
for (size_t spot = 0; spot < values.size(); spot++) {
if (spot > 0) {
cout << ", ";
}
cout << values[spot];
}
cout << "]" << endl;
}
void print(const vector<vector<int>>& grid) {
for (const vector<int>& line : grid) {
print(line);
}
}
int main() {
Solution solver;
vector<int> nums = {2, 5, 8, 12, 16, 23, 38, 56};
int target = 23;
cout << solver.search(nums, target) << endl;
return 0;
}def search(nums, target):
low = 0
high = len(nums) - 1
while low <= high:
mid = low + (high - low) // 2
if nums[mid] == target:
return mid
if target > nums[mid]:
low = mid + 1
else:
high = mid - 1
return -1
if __name__ == "__main__":
nums = [2, 5, 8, 12, 16, 23, 38, 56]
target = 23
print(search(nums, target))function search(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 (target > nums[mid]) {
low = mid + 1;
} else {
high = mid - 1;
}
}
return -1;
}
const nums = [2, 5, 8, 12, 16, 23, 38, 56];
const target = 23;
console.log(search(nums, target));