0% found this document useful (0 votes)
7 views2 pages

Binary Search Cheat Sheat

This cheat sheet outlines various binary search techniques, including standard binary search, lower and upper bounds, and searching in rotated sorted arrays. It also covers binary search on answers, floating point binary search, finding peak elements in an array, and applying binary search in a 2D matrix. Each technique is accompanied by a brief explanation and pseudocode for implementation.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
7 views2 pages

Binary Search Cheat Sheat

This cheat sheet outlines various binary search techniques, including standard binary search, lower and upper bounds, and searching in rotated sorted arrays. It also covers binary search on answers, floating point binary search, finding peak elements in an array, and applying binary search in a 2D matrix. Each technique is accompanied by a brief explanation and pseudocode for implementation.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 2

Binary Search Techniques - Cheat Sheet

1. Standard Binary Search


Used to find the index of a target in a sorted array.

while (low <= high):

mid = low + (high - low) / 2

if arr[mid] == target: return mid

elif arr[mid] < target: low = mid + 1

else: high = mid - 1

2. Lower Bound / First Occurrence


Find the first position where the target appears.

if arr[mid] >= target:

ans = mid; high = mid - 1

else:

low = mid + 1

3. Upper Bound / Last Occurrence


Find the last position where the target appears.

if arr[mid] <= target:

ans = mid; low = mid + 1

else:

high = mid - 1

4. Search in Rotated Sorted Array


Key idea: check which half is sorted.

Adjust low and high based on sorted segment and target value.

5. Binary Search on Answer (Search Space Binary Search)


Used when you have to guess the answer in a range and verify it.

Examples: Koko Eating Bananas, Minimum Days for Bouquets.

while (low < high):

mid = low + (high - low) / 2

if isPossible(mid): high = mid

else: low = mid + 1

6. Floating Point Binary Search


Used for problems requiring precision like square root, cube root.

while (high - low > eps):

mid = (low + high) / 2

if check(mid): low = mid

else: high = mid

7. Peak Element in Array


Find any peak (element greater than neighbors).

if arr[mid] < arr[mid + 1]: low = mid + 1

else: high = mid

8. Binary Search in 2D Matrix


Convert 2D matrix to 1D search.

row = mid / cols, col = mid % cols

You might also like