Browse curriculum

Binary Search

Binary Search Interview Questions: 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. Below are the binary search interview questions from LeetCode, each with a step-by-step visual solution.

20

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 interview questions: 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)
Search Insert PositionEasyΩ(log n)Θ(log n)O(log n)O(1)
First Bad VersionEasyΩ(log n)Θ(log n)O(log n)O(1)
Guess Number Higher or LowerEasyΩ(1)Θ(log n)O(log n)O(1)
Successful Pairs of Spells and PotionsMediumΩ((n + m) log m)Θ((n + m) log m)O((n + m) log m)O(log m)
Search Suggestions SystemMediumΩ((n + L) log n)Θ((n + L) log n)O((n + L) log n)O(log n)
Single Element in a Sorted ArrayMediumΩ(1)Θ(log n)O(log n)O(1)
Sqrt(x)EasyΩ(log x)Θ(log x)O(log x)O(1)
Valid Perfect SquareEasyΩ(1)Θ(log num)O(log num)O(1)
Find Peak ElementMediumΩ(log n)Θ(log n)O(log n)O(1)
Find a Peak Element IIMediumΩ(m)Θ(m log n)O(m log n)O(1)
Koko Eating Bananas (Apple Harvest)MediumΩ(n log M)Θ(n log M)O(n log M)O(1)
Split Array Largest SumHardΩ(n log S)Θ(n log S)O(n log S)O(1)
Search in Rotated Sorted ArrayMediumΩ(1)Θ(log n)O(log n)O(1)
Search in Rotated Sorted Array IIMediumΩ(1)Θ(log n)O(n)O(1)
Find Minimum in Rotated Sorted ArrayMediumΩ(1)Θ(log n)O(log n)O(1)
Search a 2D MatrixMediumΩ(1)Θ(log(m · n))O(log(m · n))O(1)
Search a 2D Matrix IIMediumΩ(1)Θ(m + n)O(m + n)O(1)
Time Based Key-Value StoreMediumΩ(1)Θ(log n)O(log n)O(n)
Median of Two Sorted ArraysHardΩ(1)Θ(log min(m, n))O(log min(m, 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 18 coding interview patterns, and its problems also appear in the DSA 75 interview sprint.

Directory

Every other coding interview pattern