Tags

Binary Search

Binary Search

2 lessons
18 problems
5 code snippets
2 question banks
11 community items

binary-search

Algorithms

2 lessons

Binary Search (Intro)

Free
Beginner

50 min

2 prereqs

Searching a sorted array of one billion elements with linear search takes up to a billion comparisons. Binary search needs about thirty. The same input, the same hardware, two algorithms with completely different scaling behavior, separated only by the assumption that the array is sorted. **Binary Search (Intro)** explains how to get that speedup and how to write the algorithm without the off-by-one errors and infinite loops that trip up almost everyone the first time. You will implement the canonical two-pointer template with `left` and `right` indices, learn why `mid = left + (right - left) / 2` matters for avoiding integer overflow, and trace the algorithm step by step on small inputs to see the search space halve each iteration. The lesson also surveys built-in support across languages (`Array.indexOf` is _not_ a binary search; Python's `bisect` is) and the most common pitfalls. In **Arrays & Strings**, you saw why indexed access on an array is `O(1)`; binary search is the first algorithm that uses that property to skip past whole regions instead of walking through them. **Big-O Notation (Upper Bound)** gave you the language `O(log n)` and the reasoning that explains why halving leads to logarithmic growth. From here you will move into **Two Pointers (Intro)**, which generalizes the same coordinated-index idea beyond exact-match searching.

Not Started

0%

Algorithms
Binary Search
Searching
Arrays
Logarithms
Time Complexity
Beginner
Free

Binary Search Templates

Intermediate

55 min

1 prereq

Standard binary search returns an arbitrary index of a target if duplicates exist, but real problems usually want the _first_ such index, the _last_ such index, or the smallest capacity that ships every package within `D` days. Each variation needs a slightly different loop condition and return value, and getting one wrong produces an off-by-one bug or an infinite loop. **Binary Search Templates** turns those variations into a small set of memorable templates. You will work through first and last occurrence with `<=` versus `<` loop conditions, lower bound and upper bound (the templates behind Python's `bisect_left` and `bisect_right`), binary search on the answer space (the "minimize the maximum" pattern that solves Koko Eating Bananas, Capacity to Ship Packages, and Split Array Largest Sum), and search in rotated sorted arrays where the invariant holds for exactly one half at each step. In **Binary Search (Intro)**, you wrote the canonical exact-match loop and learned why it is `O(log n)`. This lesson keeps the halving idea but switches the question from "is `target` here?" to "what is the smallest index that satisfies a monotonic predicate?". Next, **Linked List Algorithms** turns to pointer manipulation patterns.

Not Started

0%

Algorithms
Binary Search
Binary Search Templates
Searching
Patterns
Problem Solving
Intermediate
Premium

Practice Problems

18 problems

Binary Search

Free
Not Started
Easy

Given a sorted array of integers and a target value, return the index of the target using binary search, or -1 if not found.

Binary Search
Arrays
Searching
Beginner

822

12

Count Complete Tree Nodes

Free
Not Started
Easy

Given the root of a complete binary tree, return the number of nodes in the tree.

Binary Tree
DFS
Binary Search
Recursion
Beginner

499

7

First Bad Version

Free
Not Started
Easy

Given n versions numbered 1 to n and an API that tells whether a version is bad, find the first bad version using minimum API calls.

Binary Search
Searching
Beginner

309

9

Search Insert Position

Free
Not Started
Easy

Given a sorted array and a target value, return the index where the target is found or where it would be inserted to keep the array sorted.

Binary Search
Arrays
Searching
Beginner

365

4

Maximum Profit in Job Scheduling

Not Started
Hard

Given jobs with start times, end times, and profits, find the maximum profit you can earn by scheduling non-overlapping jobs.

Dynamic Programming
Binary Search
Sorting
Arrays
Advanced

933

13

Median of Two Sorted Arrays

Not Started
Hard

Find the median of two sorted arrays in O(log(min(m, n))) time by binary searching for the correct partition.

Binary Search
Arrays
Searching
Advanced

585

17

Swim in Rising Water

Not Started
Hard

Given an n x n grid of elevations, find the minimum time t at which you can swim from the top-left to the bottom-right corner.

Graphs
BFS
Binary Search
Heap
Shortest Path
Advanced

691

15

Find First and Last Position of Element in Sorted Array

Not Started
Medium

Given a sorted array and a target, find the starting and ending position of the target value in O(log n) time.

Binary Search
Arrays
Searching
Intermediate

623

13

Find Minimum in Rotated Sorted Array

Free
Not Started
Medium

Find the minimum element in a sorted array that has been rotated between 1 and n times, using O(log n) time.

Binary Search
Arrays
Searching
Intermediate

644

9

Find Peak Element

Not Started
Medium

Find a peak element in an array where the element is strictly greater than its neighbors. Return any peak's index in O(log n) time.

Binary Search
Arrays
Searching
Intermediate

537

2

Koko Eating Bananas

Not Started
Medium

Find the minimum eating speed at which Koko can finish all banana piles within h hours, using binary search on the answer.

Binary Search
Searching
Intermediate

422

11

Longest Increasing Subsequence

Free
Not Started
Medium

Given an integer array, return the length of the longest strictly increasing subsequence.

Dynamic Programming
Tabulation
Longest Increasing Subsequence
Binary Search
Algorithms
Intermediate

794

25

Search a 2D Matrix II

Not Started
Medium

Search for a target value in an m x n matrix where each row and each column is sorted in ascending order, using an efficient staircase approach.

Binary Search
Arrays
Searching
Intermediate

524

12

Search a 2D Matrix

Free
Not Started
Medium

Write an efficient algorithm to search for a target value in an m x n matrix where each row is sorted and the first integer of each row is greater than the last integer of the previous row.

Binary Search
Arrays
Searching
Intermediate

375

9

Search in Rotated Sorted Array

Free
Not Started
Medium

Search for a target value in a rotated sorted array of unique integers, returning its index or -1 if not found, in O(log n) time.

Binary Search
Arrays
Searching
Intermediate

1.1k

22

Sqrt(x)

Free
Not Started
Medium

Given a non-negative integer x, return the square root of x rounded down to the nearest integer. Use binary search to achieve O(log x) time without using built-in exponent functions.

Mathematics
Binary Search
Algorithms
Intermediate

492

9

Time Based Key-Value Store

Not Started
Medium

Design a key-value store that can store multiple values for the same key at different timestamps and retrieve the value at a given timestamp using binary search.

Binary Search
Hash Map / Dictionary
Searching
Intermediate

567

17

Two Sum II - Input Array Is Sorted

Free
Not Started
Medium

Given a 1-indexed sorted array, find two numbers that add up to a target and return their indices.

Two Pointers
Arrays
Binary Search
Intermediate

1k

14

Code Snippets

5 snippets
Code Snippet

Binary Search Template

Binary search is the most asked algorithm in interviews and the easiest to get wrong: off-by-one bugs, infinite loops, integer overflow on the midpoint. This snippet covers the iterative bounds template that always terminates, a recursive variant for contrast, and a found-or-insertion-point version that returns where the value would go if absent. The same skeleton powers the lower-bound and upper-bound variants in the next entry.

JavaScript
algorithms
binary-search
code-template
two-pointers

967

17

Easy
Code Snippet

Lower-Bound and Upper-Bound Binary Search

Lower-bound and upper-bound binary search are the two primitives every other range query depends on. Lower-bound returns the first index where a value could be inserted; upper-bound returns the first index strictly greater than the value. This snippet covers both forms, then composes them to count occurrences in a sorted array in O(log n).

JavaScript
algorithms
binary-search
code-template
two-pointers

1.1k

34

Medium
Code Snippet

bisect for Sorted-List Insertion

The `bisect` module is Python's binary-search-on-a-list primitive: `bisect_left` and `bisect_right` find the insertion index for a value in a sorted list in O(log n). This snippet covers the basic insertion-point query, the `insort` shortcut for keeping a list sorted as you build it, and the count-occurrences and rank-percentile recipes that fall out for free.

Python
py-standard-library
binary-search
code-template
algorithms

189

2

Medium
Code Snippet

Python Binary Search Template

Binary search runs in O(log n) over any sorted array, but the off-by-one variations bite everyone. This entry ships three runnable templates: the equality search, the lower-bound (`bisect_left`) variant, and the upper-bound (`bisect_right`) variant. Each one handles every edge case the test list throws at it.

Python
binary-search
algorithms
code-template
binary-search-templates

1k

33

Easy
Code Snippet

std::lower_bound Recipes

`std::lower_bound` returns an iterator to the first element NOT less than a target in a sorted range, while `std::upper_bound` returns the first element strictly greater. This snippet shows how to use both for sorted-insertion, range-counting, and predicate-based binary search via the comparator overload. All run in O(log n) on random-access iterators.

C++
cpp-algorithms-stl
binary-search
binary-search-templates

492

14

Medium

Community

11 items
Code Snippet

bisect Instead of sort() on Every Insert (Python)

I had a leaderboard insert loop running list.append + list.sort. Swapping to bisect.insort cut the loop from 4.2s to 0.14s on 50k inserts. The 5-line rewrite plus the keyed variant is here.

Python
binary-search
performance
sorting

935

21

4.4 (10)

May 14, 2026

by @sarahwilson

Problem
Hard
$9.99

Split Array Largest Sum

Split a non-negative integer array into k contiguous parts that minimize the maximum part sum, via binary search on the answer plus a greedy feasibility check.

binary-search
arrays
greedy

914

8

Apr 1, 2026

by @chidiweber

Problem
Easy
Free

Find Smallest Letter Greater Than Target

Classic upper_bound on a sorted character array, with a wrap-around twist that makes the binary-search invariants worth thinking through carefully.

binary-search
arrays

761

10

4.6 (13)

Mar 27, 2026

by CodeSnatch

Problem
Easy
Free

Arranging Coins

Find the largest k such that 1+2+...+k <= n, framed as a binary-search-on-answer warmup with a closed-form sanity check.

binary-search
math

484

15

4.4 (9)

Mar 12, 2026

by @elenamuller

Problem
Medium
$6.99

Snapshot Array

Implement an array-like structure with constant-time set / snap and binary-search get-at-snapshot, using per-index version lists.

data-structures
binary-search
arrays

795

12

4.3 (14)

Feb 7, 2026

by @nathanmurphy

Problem
Medium
Free

Capacity to Ship Packages Within D Days

Binary-search-on-answer for the smallest belt capacity that ships all packages in order within D days, with a linear feasibility check per candidate.

binary-search
arrays
greedy

282

2

4.5 (12)

Jan 26, 2026

by @theowatanabe

Problem
Medium
Free

Find K Closest Elements

Find a length-k window in a sorted array whose elements are closest to x, using a binary search on the LEFT edge of the window.

binary-search
two-pointers
arrays

786

19

4.5 (14)

Jan 20, 2026

by @jameszhang

Code Snippet

Binary Search on the Answer Space

I had to bin-pack 5M jobs across N machines under a wall-time budget; sort-and-greedy timed out. The fix was binary searching the makespan: a `feasible(m)` predicate plus the standard lo/hi loop turns an NP-hard scheduler into O(N log range).

JavaScript
binary-search
problem-solving
code-template

647

21

4.4 (13)

Jan 12, 2026

by @rohaneriksson

Question Bundle
Free

Binary Search Questions I Overcomplicated

Four binary search problems I made harder than they needed to be. Each shows the version I wrote in the loop and the version that should have been my first instinct, with invariants written down.

JavaScript
algorithms
binary-search
invariants

377

8

Nov 28, 2025

by @andresokonkwo

Article

Binary Search: Divide and Conquer

The template you actually need, three variations that cover most interview problems, and the off-by-one bug that catches every engineer at least once.

binary-search
binary-search-templates
divide-and-conquer
algorithms
interview-prep

905

15

4.4 (9)

Nov 25, 2025

by @leoeriksson

Problem
Medium
$5.99

Random Pick With Weight

Sample an index proportional to a positive-integer weight using a prefix-sum array and binary search.

randomized-algorithms
binary-search
prefix-sum

208

7

4.3 (11)

Nov 19, 2025

by @lilyadeyemi