Pattern 08 of 22

Binary Search Pattern: Template + 254 LeetCode Problems

Halve the search space each step — over an array, or over the answer itself.

Easy
31
Medium
138
Hard
85
Time
O(log n)

What the binary search pattern is

Binary search needs a sorted array far less than it needs a monotone predicate — some property that is false for every candidate below a threshold and true for every candidate above it. Once you can write that predicate, you can bisect anything, including a range of possible answers that is nowhere stored in memory: guess a capacity, ask whether the shipment fits, and move the bound. Most binary search bugs are off-by-one errors in the exit condition, and the cure is to stop searching for a value and search for a boundary instead. Keep the loop as `while lo < hi`, never write `mid - 1` on the side you are keeping, and let the loop end when the two bounds meet — the survivor is the smallest input for which the predicate holds. That single shape covers first occurrence, last occurrence, insertion point and minimum feasible answer, so there is only one template to remember and it terminates by construction.

When to use it

  • The array is sorted, or rotated-sorted, and you want a position rather than a scan.
  • The answer is a number in a known range and checking a candidate is cheaper than finding it.
  • The phrase "minimum largest", "maximum smallest", or "minimise the maximum" appears in the statement.
  • A brute force over the answer range would work but is one order too slow.

The binary search template in Python

The shape, not a solution to any one problem. Adapt the condition and the summary being maintained; the skeleton stays the same across the 254 problems listed below.

PythonBinary Search template
def smallest_feasible(low, high, feasible):
    """Smallest x in [low, high] with feasible(x) true, assuming it is monotone."""
    while low < high:
        mid = low + (high - low) // 2      # floor: biases toward low, never overflows
        if feasible(mid):
            high = mid                     # mid works, so the answer is mid or lower
        else:
            low = mid + 1                  # mid fails, so the answer is strictly higher
    return low

Complexity characteristics

Time
O(log n)
Auxiliary space
O(1)

Every iteration discards half of what is left, so the loop runs log₂ n times. When the search is over a range of possible answers rather than over an array, the cost is O(log W) iterations times whatever the feasibility check costs, where W is the width of the range — that product is the figure to quote, because the check is usually a linear scan and the real complexity is O(n log W). The iterative form uses constant space.

Eyes only

Meet the binary search problem you did not practise.

In the live round, Stealth Interview reads the problem off your screen, returns a working solution with a step-by-step explanation and its time and space complexity, and transcribes what the interviewer says. It's a desktop app for macOS and Windows, invisible to screen sharing.

All 254 binary search LeetCode problems

Every problem in the library the binary search pattern applies to, grouped by LeetCode's own difficulty rating. 213 of the 254 carry a complete Python solution with a worked example and complexity analysis; the rest are listed for completeness, with the LeetCode Premium ones marked.

Related LeetCode topics

Easy (31)

Easy problems
No.Problem
0035Search Insert Position
0069Sqrt(x)
0222Count Complete Tree Nodes
0268Missing Number
0278First Bad Version
0349Intersection of Two Arrays
0350Intersection of Two Arrays II
0367Valid Perfect Square
0374Guess Number Higher or Lower
0441Arranging Coins
0704Binary Search
0744Find Smallest Letter Greater Than Target
0270Closest Binary Search Tree ValuePremium
0888Fair Candy Swap
1064Fixed PointPremium
1099Two Sum Less Than KPremium
1150Check If a Number Is Majority Element in a Sorted ArrayPremium
1213Intersection of Three Sorted ArraysPremium
1337The K Weakest Rows in a Matrix
1346Check If N and Its Double Exist
1351Count Negative Numbers in a Sorted Matrix
1385Find the Distance Value Between Two Arrays
1539Kth Missing Positive Number
1608Special Array With X Elements Greater Than or Equal X
2089Find Target Indices After Sorting Array
2389Longest Subsequence With Limited Sum
2529Maximum Count of Positive Integer and Negative Integer
2540Minimum Common Value
2774Array Upper BoundPremium
2824Count Pairs Whose Sum is Less than Target
2970Count the Number of Incremovable Subarrays I

Medium (138)

Medium problems
No.Problem
0033Search in Rotated Sorted Array
0034Find First and Last Position of Element in Sorted Array
0074Search a 2D Matrix
0081Search in Rotated Sorted Array II
0153Find Minimum in Rotated Sorted Array
0162Find Peak Element
0167Two Sum II - Input Array Is Sorted
0209Minimum Size Subarray Sum
0240Search a 2D Matrix II
0275H-Index II
0287Find the Duplicate Number
0300Longest Increasing Subsequence
0378Kth Smallest Element in a Sorted Matrix
0400Nth Digit
0436Find Right Interval
0456132 Pattern
0475Heaters
0497Random Point in Non-overlapping Rectangles
0528Random Pick with Weight
0532K-diff Pairs in an Array
0540Single Element in a Sorted Array
0611Valid Triangle Number
0633Sum of Square Numbers
0658Find K Closest Elements
0713Subarray Product Less Than K
0718Maximum Length of Repeated Subarray
0729My Calendar I
0731My Calendar II
0875Koko Eating Bananas
0981Time Based Key-Value Store
1004Max Consecutive Ones III
1268Search Suggestions System
2300Successful Pairs of Spells and Potions
02593Sum SmallerPremium
0362Design Hit CounterPremium
0702Search in a Sorted Array of Unknown SizePremium
0754Reach a Number
0786K-th Smallest Prime Fraction
0792Number of Matching Subsequences
0825Friends Of Appropriate Ages
0826Most Profit Assigning Work
0852Peak Index in a Mountain Array
0911Online Election
1011Capacity To Ship Packages Within D Days
1027Longest Arithmetic Subsequence
1055Shortest Way to Form StringPremium
1060Missing Element in Sorted ArrayPremium
1062Longest Repeating SubstringPremium
1102Path With Maximum Minimum ValuePremium
1146Snapshot Array
1170Compare Strings by Frequency of the Smallest Character
1182Shortest Distance to Target ColorPremium
1198Find Smallest Common Element in All RowsPremium
1201Ugly Number III
1208Get Equal Substrings Within Budget
1214Two Sum BSTsPremium
1237Find Positive Integer Solution for a Given Equation
1283Find the Smallest Divisor Given a Threshold
1292Maximum Side Length of a Square with Sum Less than or Equal to Threshold
1300Sum of Mutated Array Closest to Target
1348Tweet Counts Per Frequency
1428Leftmost Column with at Least a OnePremium
1477Find Two Non-overlapping Sub-arrays Each With Target Sum
1482Minimum Number of Days to Make m Bouquets
1488Avoid Flood in The City
1498Number of Subsequences That Satisfy the Given Sum Condition
1508Range Sum of Sorted Subarray Sums
1533Find the Index of the Large IntegerPremium
1552Magnetic Force Between Two Balls
1562Find Latest Group of Size M
1574Shortest Subarray to be Removed to Make Array Sorted
1618Maximum Font to Fit a Sentence in a ScreenPremium
1631Path With Minimum Effort
1648Sell Diminishing-Valued Colored Balls
1658Minimum Operations to Reduce X to Zero
1712Ways to Split Array Into Three Subarrays
1760Minimum Limit of Balls in a Bag
1802Maximum Value at a Given Index in a Bounded Array
1818Minimum Absolute Sum Difference
1838Frequency of the Most Frequent Element
1855Maximum Distance Between a Pair of Values
1870Minimum Speed to Arrive on Time
1885Count Pairs in Two ArraysPremium
1891Cutting RibbonsPremium
1894Find the Student that Will Replace the Chalk
1898Maximum Number of Removable Characters
1901Find a Peak Element II
1918Kth Smallest Subarray SumPremium
1954Minimum Garden Perimeter to Collect Enough Apples
1966Binary Searchable Numbers in an Unsorted ArrayPremium
2008Maximum Earnings From Taxi
2024Maximize the Confusion of an Exam
2031Count Subarrays With More Ones Than ZerosPremium
2054Two Best Non-Overlapping Events
2055Plates Between Candles
2064Minimized Maximum of Products Distributed to Any Store
2070Most Beautiful Item for Each Query
2080Range Frequency Queries
2137Pour Water Between Buckets to Make Water Levels EqualPremium
2187Minimum Time to Complete Trips
2226Maximum Candies Allocated to K Children
2250Count Number of Rectangles Containing Each Point
2271Maximum White Tiles Covered by a Carpet
2332The Latest Time to Catch a Bus
2333Minimum Sum of Squared Difference
2358Maximum Number of Groups Entering a Competition
2387Median of a Row Wise Sorted MatrixPremium
2411Smallest Subarrays With Maximum Bitwise OR
2424Longest Uploaded Prefix
2439Minimize Maximum of Array
2476Closest Nodes Queries in a Binary Search Tree
2498Frog Jump II
2501Longest Square Streak in an Array
2513Minimize the Maximum of Two Arrays
2517Maximum Tastiness of Candy Basket
2554Maximum Number of Integers to Choose From a Range I
2555Maximize Win From Two Segments
2557Maximum Number of Integers to Choose From a Range IIPremium
2560House Robber IV
2563Count the Number of Fair Pairs
2576Find the Maximum Number of Marked Indices
2594Minimum Time to Repair Cars
2601Prime Subtraction Operation
2602Minimum Operations to Make All Array Elements Equal
2616Minimize the Maximum Difference of Pairs
2779Maximum Beauty of an Array After Applying Operation
2812Find the Safest Path in a Grid
2817Minimum Absolute Difference Between Elements With Constraint
2826Sorting Three Groups
2830Maximize the Profit as the Salesman
2831Find the Longest Equal Subarray
2838Maximum Coins Heroes Can CollectPremium
2856Minimum Array Length After Pair Removals
2861Maximum Number of Alloys
2936Number of Equal Numbers BlocksPremium
2967Minimum Cost to Make Array Equalindromic
2981Find Longest Special Substring That Occurs Thrice I
2982Find Longest Special Substring That Occurs Thrice II

Hard (85)

Hard problems
No.Problem
0004Median of Two Sorted Arrays
0154Find Minimum in Rotated Sorted Array II
0315Count of Smaller Numbers After Self
0327Count of Range Sum
0352Data Stream as Disjoint Intervals
0354Russian Doll Envelopes
0363Max Sum of Rectangle No Larger Than K
0410Split Array Largest Sum
0483Smallest Good Base
0493Reverse Pairs
0668Kth Smallest Number in Multiplication Table
0710Random Pick with Blacklist
0719Find K-th Smallest Pair Distance
0732My Calendar III
0778Swim in Rising Water
1235Maximum Profit in Job Scheduling
1851Minimum Interval to Include Each Query
0302Smallest Rectangle Enclosing Black PixelsPremium
0644Maximum Average Subarray IIPremium
0774Minimize Max Distance to Gas StationPremium
0793Preimage Size of Factorial Zeroes Function
0862Shortest Subarray with Sum at Least K
0878Nth Magical Number
0887Super Egg Drop
0902Numbers At Most N Given Digit Set
1044Longest Duplicate Substring
1095Find in Mountain Array
1157Online Majority Element In Subarray
1187Make Array Strictly Increasing
1231Divide ChocolatePremium
1439Find the Kth Smallest Sum of a Matrix With Sorted Rows
1483Kth Ancestor of a Tree Node
1521Find a Value of a Mysterious Function Closest to Target
1649Create Sorted Array through Instructions
1671Minimum Number of Removals to Make Mountain Array
1713Minimum Operations to Make a Subsequence
1739Building Boxes
1751Maximum Number of Events That Can Be Attended II
1782Count Pairs Of Nodes
1793Maximum Score of a Good Subarray
1847Closest Room
1862Sum of Floored Pairs
1889Minimum Space Wasted From Packaging
1923Longest Common Subpath
1932Merge BSTs to Create Single BST
1956Minimum Time For K Virus Variants to SpreadPremium
1964Find the Longest Valid Obstacle Course at Each Position
1970Last Day Where You Can Still Cross
2009Minimum Number of Operations to Make Array Continuous
2035Partition Array Into Two Arrays to Minimize Sum Difference
2040Kth Smallest Product of Two Sorted Arrays
2071Maximum Number of Tasks You Can Assign
2106Maximum Fruits Harvested After at Most K Steps
2111Minimum Operations to Make the Array K-Increasing
2141Maximum Running Time of N Computers
2179Count Good Triplets in an Array
2223Sum of Scores of Built Strings
2234Maximum Total Beauty of the Gardens
2251Number of Flowers in Full Bloom
2258Escape the Spreading Fire
2286Booking Concert Tickets in Groups
2302Count Subarrays With Score Less Than K
2354Number of Excellent Pairs
2398Maximum Number of Robots Within Budget
2426Number of Pairs Satisfying Inequality
2448Minimum Cost to Make Array Equal
2454Next Greater Element IV
2468Split Message Based on Limit
2519Count the Number of K-Big IndicesPremium
2528Maximize the Minimum Powered City
2565Subsequence With the Minimum Score
2589Minimum Time to Complete All Tasks
2604Minimum Time to Eat All GrainsPremium
2659Make Array Empty
2702Minimum Operations to Make Numbers Non-positivePremium
2713Maximum Strictly Increasing Cells in a Matrix
2736Maximum Sum Queries
2790Maximum Number of Groups With Increasing Length
2819Minimum Relative Loss After Buying ChocolatesPremium
2926Maximum Balanced Subsequence Sum
2940Find Building Where Alice and Bob Can Meet
2941Maximum GCD-Sum of a SubarrayPremium
2945Find Maximum Non-decreasing Array Length
2968Apply Operations to Maximize Frequency Score
2972Count the Number of Incremovable Subarrays II

Binary Search pattern FAQ

What is the binary search pattern?

Binary search needs a sorted array far less than it needs a monotone predicate — some property that is false for every candidate below a threshold and true for every candidate above it.

How many LeetCode problems use the binary search pattern?

This page lists 254 LeetCode problems that the binary search pattern applies to: 31 Easy, 138 Medium and 85 Hard. 213 of them carry a complete Python solution with complexity analysis.

What is the time complexity of the binary search pattern?

O(log n) time and O(1) space. Every iteration discards half of what is left, so the loop runs log₂ n times. When the search is over a range of possible answers rather than over an array, the cost is O(log W) iterations times whatever the feasibility check costs, where W is the width of the range — that product is the figure to quote, because the check is usually a linear scan and the real complexity is O(n log W). The iterative form uses constant space.

When should I use the binary search pattern in an interview?

The array is sorted, or rotated-sorted, and you want a position rather than a scan. The answer is a number in a known range and checking a candidate is cheaper than finding it.

Which binary search problem should I start with?

LeetCode 35. Search Insert Position is the lowest-numbered Easy problem on this page, which makes it the usual starting point: the technique is visible without the problem's own complications getting in the way.

What patterns are related to binary search?

Two Pointers, Sorting, Greedy, Heap / Priority Queue. Problems frequently sit in more than one of these, and the overlap is where the interesting follow-up questions come from.

More ways in: all 22 patterns, the curated study lists, or the full problem list.