Browse curriculum

Binary Search

The Binary Search Pattern

Halve the search space on every comparison. The powerful form in interviews is not searching a sorted array but binary searching the answer itself: guess a value, ask a yes/no feasibility question, and discard half the range of possible answers.

3

Interactive problems

1

Free to open

Recognise

How do you recognise a binary search problem?

The data is sorted or rotated-sorted, or — more often — the answer lies in a numeric range and there is a monotonic feasibility check ("if capacity C works, C+1 also works"). "Minimum capacity to ship packages in D days" is binary search on the answer.

Complexity

What is the time complexity of the binary search pattern?

O(log n) per search. Binary searching an answer range costs O(log(range) × cost of the feasibility check).

Problems

Binary Search practice problems

Each problem pairs a worked explanation with an interactive visualizer you step through yourself, plus the implementation in JavaScript, Python, Java and C++.

Complexity

Binary Search problems by difficulty and complexity

The difficulty, running time and extra space of every binary search solution on this page, as each lesson derives them.

LessonDifficultyBestAverageWorstSpace
Binary SearchEasyΩ(1)Θ(log n)O(log n)O(1)
Apple Harvest (Koko Variant)MediumΩ(n log M)Θ(n log M)O(n log M)O(1)
Search in Rotated Sorted ArrayMediumΩ(1)Θ(log n)O(log n)O(1)
Curriculum

The underlying technique is covered from first principles in the binary search lesson in the DSA visualizer curriculum. Binary Search is one of the 17 coding interview patterns, and its problems also appear in the DSA 75 interview sprint.

Directory

Every other coding interview pattern