Binary Search Pattern: Template + 254 LeetCode Problems

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

  • 31 Easy
  • 138 Medium
  • 85 Hard
  • O(log n) time

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.

Binary Search — Python 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.

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)

#ProblemDifficultyTopics
35Search Insert PositionEasyArray, Binary Search
69Sqrt(x)EasyMath, Binary Search
222Count Complete Tree NodesEasyBit Manipulation, Tree, Binary Search +1
268Missing NumberEasyBit Manipulation, Array, Hash Table +3
278First Bad VersionEasyBinary Search, Interactive
349Intersection of Two ArraysEasyArray, Hash Table, Two Pointers +2
350Intersection of Two Arrays IIEasyArray, Hash Table, Two Pointers +2
367Valid Perfect SquareEasyMath, Binary Search
374Guess Number Higher or LowerEasyBinary Search, Interactive
441Arranging CoinsEasyMath, Binary Search
704Binary SearchEasyArray, Binary Search
744Find Smallest Letter Greater Than TargetEasyArray, Binary Search
270Closest Binary Search Tree ValuePremiumEasyTree, Depth-First Search, Binary Search Tree +2
888Fair Candy SwapEasyArray, Hash Table, Binary Search +1
1064Fixed PointPremiumEasyArray, Binary Search
1099Two Sum Less Than KPremiumEasyArray, Two Pointers, Binary Search +1
1150Check If a Number Is Majority Element in a Sorted ArrayPremiumEasyArray, Binary Search
1213Intersection of Three Sorted ArraysPremiumEasyArray, Hash Table, Binary Search +1
1337The K Weakest Rows in a MatrixEasyArray, Binary Search, Matrix +2
1346Check If N and Its Double ExistEasyArray, Hash Table, Two Pointers +2
1351Count Negative Numbers in a Sorted MatrixEasyArray, Binary Search, Matrix
1385Find the Distance Value Between Two ArraysEasyArray, Two Pointers, Binary Search +1
1539Kth Missing Positive NumberEasyArray, Binary Search
1608Special Array With X Elements Greater Than or Equal XEasyArray, Binary Search, Sorting
2089Find Target Indices After Sorting ArrayEasyArray, Binary Search, Sorting
2389Longest Subsequence With Limited SumEasyGreedy, Array, Binary Search +2
2529Maximum Count of Positive Integer and Negative IntegerEasyArray, Binary Search, Counting
2540Minimum Common ValueEasyArray, Hash Table, Two Pointers +1
2774Array Upper BoundPremiumEasyJavaScript
2824Count Pairs Whose Sum is Less than TargetEasyArray, Two Pointers, Binary Search +1
2970Count the Number of Incremovable Subarrays IEasyArray, Two Pointers, Binary Search +1

Medium (138)

#ProblemDifficultyTopics
33Search in Rotated Sorted ArrayMediumArray, Binary Search
34Find First and Last Position of Element in Sorted ArrayMediumArray, Binary Search
74Search a 2D MatrixMediumArray, Binary Search, Matrix
81Search in Rotated Sorted Array IIMediumArray, Binary Search
153Find Minimum in Rotated Sorted ArrayMediumArray, Binary Search
162Find Peak ElementMediumArray, Binary Search
167Two Sum II - Input Array Is SortedMediumArray, Two Pointers, Binary Search
209Minimum Size Subarray SumMediumArray, Binary Search, Prefix Sum +1
240Search a 2D Matrix IIMediumArray, Binary Search, Divide and Conquer +1
275H-Index IIMediumArray, Binary Search
287Find the Duplicate NumberMediumBit Manipulation, Array, Two Pointers +1
300Longest Increasing SubsequenceMediumArray, Binary Search, Dynamic Programming
378Kth Smallest Element in a Sorted MatrixMediumArray, Binary Search, Matrix +2
400Nth DigitMediumMath, Binary Search
436Find Right IntervalMediumArray, Binary Search, Sorting
456132 PatternMediumStack, Array, Binary Search +2
475HeatersMediumArray, Two Pointers, Binary Search +1
497Random Point in Non-overlapping RectanglesMediumReservoir Sampling, Array, Math +4
528Random Pick with WeightMediumArray, Math, Binary Search +2
532K-diff Pairs in an ArrayMediumArray, Hash Table, Two Pointers +2
540Single Element in a Sorted ArrayMediumArray, Binary Search
611Valid Triangle NumberMediumGreedy, Array, Two Pointers +2
633Sum of Square NumbersMediumMath, Two Pointers, Binary Search
658Find K Closest ElementsMediumArray, Two Pointers, Binary Search +3
713Subarray Product Less Than KMediumArray, Binary Search, Prefix Sum +1
718Maximum Length of Repeated SubarrayMediumArray, Binary Search, Dynamic Programming +3
729My Calendar IMediumDesign, Segment Tree, Array +2
731My Calendar IIMediumDesign, Segment Tree, Array +3
875Koko Eating BananasMediumArray, Binary Search
981Time Based Key-Value StoreMediumDesign, Hash Table, String +1
1004Max Consecutive Ones IIIMediumArray, Binary Search, Prefix Sum +1
1268Search Suggestions SystemMediumTrie, Array, String +3
2300Successful Pairs of Spells and PotionsMediumArray, Two Pointers, Binary Search +1
2593Sum SmallerPremiumMediumArray, Two Pointers, Binary Search +1
362Design Hit CounterPremiumMediumDesign, Queue, Array +2
702Search in a Sorted Array of Unknown SizePremiumMediumArray, Binary Search, Interactive
754Reach a NumberMediumMath, Binary Search
786K-th Smallest Prime FractionMediumArray, Two Pointers, Binary Search +2
792Number of Matching SubsequencesMediumTrie, Array, Hash Table +4
825Friends Of Appropriate AgesMediumArray, Two Pointers, Binary Search +1
826Most Profit Assigning WorkMediumGreedy, Array, Two Pointers +2
852Peak Index in a Mountain ArrayMediumArray, Binary Search
911Online ElectionMediumDesign, Array, Hash Table +1
1011Capacity To Ship Packages Within D DaysMediumArray, Binary Search
1027Longest Arithmetic SubsequenceMediumArray, Hash Table, Binary Search +1
1055Shortest Way to Form StringPremiumMediumGreedy, Two Pointers, String +1
1060Missing Element in Sorted ArrayPremiumMediumArray, Binary Search
1062Longest Repeating SubstringPremiumMediumString, Binary Search, Dynamic Programming +3
1102Path With Maximum Minimum ValuePremiumMediumDepth-First Search, Breadth-First Search, Union Find +4
1146Snapshot ArrayMediumDesign, Array, Hash Table +1
1170Compare Strings by Frequency of the Smallest CharacterMediumArray, Hash Table, String +2
1182Shortest Distance to Target ColorPremiumMediumArray, Binary Search, Dynamic Programming
1198Find Smallest Common Element in All RowsPremiumMediumArray, Hash Table, Binary Search +2
1201Ugly Number IIIMediumMath, Binary Search, Combinatorics +1
1208Get Equal Substrings Within BudgetMediumString, Binary Search, Prefix Sum +1
1214Two Sum BSTsPremiumMediumStack, Tree, Depth-First Search +4
1237Find Positive Integer Solution for a Given EquationMediumMath, Two Pointers, Binary Search +1
1283Find the Smallest Divisor Given a ThresholdMediumArray, Binary Search
1292Maximum Side Length of a Square with Sum Less than or Equal to ThresholdMediumArray, Binary Search, Matrix +1
1300Sum of Mutated Array Closest to TargetMediumArray, Binary Search, Sorting
1348Tweet Counts Per FrequencyMediumDesign, Hash Table, String +3
1428Leftmost Column with at Least a OnePremiumMediumArray, Binary Search, Interactive +1
1477Find Two Non-overlapping Sub-arrays Each With Target SumMediumArray, Hash Table, Binary Search +2
1482Minimum Number of Days to Make m BouquetsMediumArray, Binary Search
1488Avoid Flood in The CityMediumGreedy, Array, Hash Table +2
1498Number of Subsequences That Satisfy the Given Sum ConditionMediumArray, Two Pointers, Binary Search +1
1508Range Sum of Sorted Subarray SumsMediumArray, Two Pointers, Binary Search +2
1533Find the Index of the Large IntegerPremiumMediumArray, Binary Search, Interactive
1552Magnetic Force Between Two BallsMediumArray, Binary Search, Sorting
1562Find Latest Group of Size MMediumArray, Hash Table, Binary Search +1
1574Shortest Subarray to be Removed to Make Array SortedMediumStack, Array, Two Pointers +2
1618Maximum Font to Fit a Sentence in a ScreenPremiumMediumArray, String, Binary Search +1
1631Path With Minimum EffortMediumDepth-First Search, Breadth-First Search, Union Find +4
1648Sell Diminishing-Valued Colored BallsMediumGreedy, Array, Math +3
1658Minimum Operations to Reduce X to ZeroMediumArray, Hash Table, Binary Search +2
1712Ways to Split Array Into Three SubarraysMediumArray, Two Pointers, Binary Search +1
1760Minimum Limit of Balls in a BagMediumArray, Binary Search
1802Maximum Value at a Given Index in a Bounded ArrayMediumGreedy, Math, Binary Search
1818Minimum Absolute Sum DifferenceMediumArray, Binary Search, Ordered Set +1
1838Frequency of the Most Frequent ElementMediumGreedy, Array, Binary Search +3
1855Maximum Distance Between a Pair of ValuesMediumArray, Two Pointers, Binary Search
1870Minimum Speed to Arrive on TimeMediumArray, Binary Search
1885Count Pairs in Two ArraysPremiumMediumArray, Two Pointers, Binary Search +1
1891Cutting RibbonsPremiumMediumArray, Binary Search
1894Find the Student that Will Replace the ChalkMediumArray, Binary Search, Prefix Sum +1
1898Maximum Number of Removable CharactersMediumArray, Two Pointers, String +1
1901Find a Peak Element IIMediumArray, Binary Search, Matrix
1918Kth Smallest Subarray SumPremiumMediumArray, Binary Search, Sliding Window
1954Minimum Garden Perimeter to Collect Enough ApplesMediumMath, Binary Search
1966Binary Searchable Numbers in an Unsorted ArrayPremiumMediumArray, Binary Search
2008Maximum Earnings From TaxiMediumArray, Hash Table, Binary Search +2
2024Maximize the Confusion of an ExamMediumString, Binary Search, Prefix Sum +1
2031Count Subarrays With More Ones Than ZerosPremiumMediumBinary Indexed Tree, Segment Tree, Array +5
2054Two Best Non-Overlapping EventsMediumArray, Binary Search, Dynamic Programming +2
2055Plates Between CandlesMediumArray, String, Binary Search +1
2064Minimized Maximum of Products Distributed to Any StoreMediumGreedy, Array, Binary Search
2070Most Beautiful Item for Each QueryMediumArray, Binary Search, Sorting
2080Range Frequency QueriesMediumDesign, Segment Tree, Array +2
2137Pour Water Between Buckets to Make Water Levels EqualPremiumMediumArray, Binary Search
2187Minimum Time to Complete TripsMediumArray, Binary Search
2226Maximum Candies Allocated to K ChildrenMediumArray, Binary Search
2250Count Number of Rectangles Containing Each PointMediumBinary Indexed Tree, Array, Hash Table +2
2271Maximum White Tiles Covered by a CarpetMediumGreedy, Array, Binary Search +3
2332The Latest Time to Catch a BusMediumArray, Two Pointers, Binary Search +1
2333Minimum Sum of Squared DifferenceMediumGreedy, Array, Binary Search +2
2358Maximum Number of Groups Entering a CompetitionMediumGreedy, Array, Math +1
2387Median of a Row Wise Sorted MatrixPremiumMediumArray, Binary Search, Matrix
2411Smallest Subarrays With Maximum Bitwise ORMediumBit Manipulation, Array, Binary Search +1
2424Longest Uploaded PrefixMediumUnion Find, Design, Binary Indexed Tree +5
2439Minimize Maximum of ArrayMediumGreedy, Array, Binary Search +2
2476Closest Nodes Queries in a Binary Search TreeMediumTree, Depth-First Search, Binary Search Tree +3
2498Frog Jump IIMediumGreedy, Array, Binary Search
2501Longest Square Streak in an ArrayMediumArray, Hash Table, Binary Search +2
2513Minimize the Maximum of Two ArraysMediumMath, Binary Search, Number Theory
2517Maximum Tastiness of Candy BasketMediumGreedy, Array, Binary Search +1
2554Maximum Number of Integers to Choose From a Range IMediumGreedy, Array, Hash Table +2
2555Maximize Win From Two SegmentsMediumArray, Binary Search, Sliding Window
2557Maximum Number of Integers to Choose From a Range IIPremiumMediumGreedy, Array, Binary Search +1
2560House Robber IVMediumGreedy, Array, Binary Search +1
2563Count the Number of Fair PairsMediumArray, Two Pointers, Binary Search +1
2576Find the Maximum Number of Marked IndicesMediumGreedy, Array, Two Pointers +2
2594Minimum Time to Repair CarsMediumArray, Binary Search
2601Prime Subtraction OperationMediumGreedy, Array, Math +2
2602Minimum Operations to Make All Array Elements EqualMediumArray, Binary Search, Prefix Sum +1
2616Minimize the Maximum Difference of PairsMediumGreedy, Array, Binary Search +2
2779Maximum Beauty of an Array After Applying OperationMediumArray, Binary Search, Sorting +1
2812Find the Safest Path in a GridMediumBreadth-First Search, Union Find, Array +3
2817Minimum Absolute Difference Between Elements With ConstraintMediumArray, Binary Search, Ordered Set
2826Sorting Three GroupsMediumArray, Binary Search, Dynamic Programming
2830Maximize the Profit as the SalesmanMediumArray, Hash Table, Binary Search +2
2831Find the Longest Equal SubarrayMediumArray, Hash Table, Binary Search +1
2838Maximum Coins Heroes Can CollectPremiumMediumArray, Two Pointers, Binary Search +2
2856Minimum Array Length After Pair RemovalsMediumGreedy, Array, Hash Table +3
2861Maximum Number of AlloysMediumArray, Binary Search
2936Number of Equal Numbers BlocksPremiumMediumArray, Binary Search, Interactive
2967Minimum Cost to Make Array EqualindromicMediumGreedy, Array, Math +2
2981Find Longest Special Substring That Occurs Thrice IMediumHash Table, String, Binary Search +2
2982Find Longest Special Substring That Occurs Thrice IIMediumHash Table, String, Binary Search +2

Hard (85)

#ProblemDifficultyTopics
4Median of Two Sorted ArraysHardArray, Binary Search, Divide and Conquer
154Find Minimum in Rotated Sorted Array IIHardArray, Binary Search
315Count of Smaller Numbers After SelfHardBinary Indexed Tree, Segment Tree, Array +4
327Count of Range SumHardBinary Indexed Tree, Segment Tree, Array +4
352Data Stream as Disjoint IntervalsHardUnion Find, Design, Hash Table +3
354Russian Doll EnvelopesHardArray, Binary Search, Dynamic Programming +1
363Max Sum of Rectangle No Larger Than KHardArray, Binary Search, Matrix +2
410Split Array Largest SumHardGreedy, Array, Binary Search +2
483Smallest Good BaseHardMath, Binary Search
493Reverse PairsHardBinary Indexed Tree, Segment Tree, Array +4
668Kth Smallest Number in Multiplication TableHardMath, Binary Search
710Random Pick with BlacklistHardArray, Hash Table, Math +3
719Find K-th Smallest Pair DistanceHardArray, Two Pointers, Binary Search +1
732My Calendar IIIHardDesign, Segment Tree, Binary Search +2
778Swim in Rising WaterHardDepth-First Search, Breadth-First Search, Union Find +4
1235Maximum Profit in Job SchedulingHardArray, Binary Search, Dynamic Programming +1
1851Minimum Interval to Include Each QueryHardArray, Binary Search, Sorting +2
302Smallest Rectangle Enclosing Black PixelsPremiumHardDepth-First Search, Breadth-First Search, Array +2
644Maximum Average Subarray IIPremiumHardArray, Binary Search, Prefix Sum
774Minimize Max Distance to Gas StationPremiumHardArray, Binary Search
793Preimage Size of Factorial Zeroes FunctionHardMath, Binary Search
862Shortest Subarray with Sum at Least KHardQueue, Array, Binary Search +4
878Nth Magical NumberHardMath, Binary Search
887Super Egg DropHardMath, Binary Search, Dynamic Programming
902Numbers At Most N Given Digit SetHardArray, Math, String +2
1044Longest Duplicate SubstringHardString, Binary Search, Suffix Array +3
1095Find in Mountain ArrayHardArray, Binary Search, Interactive
1157Online Majority Element In SubarrayHardDesign, Binary Indexed Tree, Segment Tree +2
1187Make Array Strictly IncreasingHardArray, Binary Search, Dynamic Programming +1
1231Divide ChocolatePremiumHardArray, Binary Search
1439Find the Kth Smallest Sum of a Matrix With Sorted RowsHardArray, Binary Search, Matrix +1
1483Kth Ancestor of a Tree NodeHardBit Manipulation, Tree, Depth-First Search +4
1521Find a Value of a Mysterious Function Closest to TargetHardBit Manipulation, Segment Tree, Array +1
1649Create Sorted Array through InstructionsHardBinary Indexed Tree, Segment Tree, Array +4
1671Minimum Number of Removals to Make Mountain ArrayHardGreedy, Array, Binary Search +1
1713Minimum Operations to Make a SubsequenceHardGreedy, Array, Hash Table +1
1739Building BoxesHardGreedy, Math, Binary Search
1751Maximum Number of Events That Can Be Attended IIHardArray, Binary Search, Dynamic Programming +1
1782Count Pairs Of NodesHardGraph, Array, Hash Table +4
1793Maximum Score of a Good SubarrayHardStack, Array, Two Pointers +2
1847Closest RoomHardArray, Binary Search, Ordered Set +1
1862Sum of Floored PairsHardArray, Math, Binary Search +1
1889Minimum Space Wasted From PackagingHardArray, Binary Search, Prefix Sum +1
1923Longest Common SubpathHardArray, Binary Search, Suffix Array +2
1932Merge BSTs to Create Single BSTHardTree, Depth-First Search, Hash Table +2
1956Minimum Time For K Virus Variants to SpreadPremiumHardGeometry, Array, Math +2
1964Find the Longest Valid Obstacle Course at Each PositionHardBinary Indexed Tree, Array, Binary Search
1970Last Day Where You Can Still CrossHardDepth-First Search, Breadth-First Search, Union Find +3
2009Minimum Number of Operations to Make Array ContinuousHardArray, Hash Table, Binary Search +1
2035Partition Array Into Two Arrays to Minimize Sum DifferenceHardBit Manipulation, Array, Two Pointers +4
2040Kth Smallest Product of Two Sorted ArraysHardArray, Binary Search
2071Maximum Number of Tasks You Can AssignHardGreedy, Queue, Array +4
2106Maximum Fruits Harvested After at Most K StepsHardArray, Binary Search, Prefix Sum +1
2111Minimum Operations to Make the Array K-IncreasingHardArray, Binary Search
2141Maximum Running Time of N ComputersHardGreedy, Array, Binary Search +1
2179Count Good Triplets in an ArrayHardBinary Indexed Tree, Segment Tree, Array +4
2223Sum of Scores of Built StringsHardString, Binary Search, String Matching +3
2234Maximum Total Beauty of the GardensHardGreedy, Array, Two Pointers +4
2251Number of Flowers in Full BloomHardArray, Hash Table, Binary Search +3
2258Escape the Spreading FireHardBreadth-First Search, Array, Binary Search +1
2286Booking Concert Tickets in GroupsHardDesign, Binary Indexed Tree, Segment Tree +1
2302Count Subarrays With Score Less Than KHardArray, Binary Search, Prefix Sum +1
2354Number of Excellent PairsHardBit Manipulation, Array, Hash Table +1
2398Maximum Number of Robots Within BudgetHardQueue, Array, Binary Search +4
2426Number of Pairs Satisfying InequalityHardBinary Indexed Tree, Segment Tree, Array +4
2448Minimum Cost to Make Array EqualHardGreedy, Array, Binary Search +2
2454Next Greater Element IVHardStack, Array, Binary Search +3
2468Split Message Based on LimitHardString, Binary Search, Enumeration
2519Count the Number of K-Big IndicesPremiumHardBinary Indexed Tree, Segment Tree, Array +4
2528Maximize the Minimum Powered CityHardGreedy, Queue, Array +3
2565Subsequence With the Minimum ScoreHardTwo Pointers, String, Binary Search
2589Minimum Time to Complete All TasksHardStack, Greedy, Array +2
2604Minimum Time to Eat All GrainsPremiumHardArray, Two Pointers, Binary Search +1
2659Make Array EmptyHardGreedy, Binary Indexed Tree, Segment Tree +4
2702Minimum Operations to Make Numbers Non-positivePremiumHardArray, Binary Search
2713Maximum Strictly Increasing Cells in a MatrixHardMemoization, Array, Hash Table +5
2736Maximum Sum QueriesHardStack, Binary Indexed Tree, Segment Tree +4
2790Maximum Number of Groups With Increasing LengthHardGreedy, Array, Math +2
2819Minimum Relative Loss After Buying ChocolatesPremiumHardArray, Binary Search, Prefix Sum +1
2926Maximum Balanced Subsequence SumHardBinary Indexed Tree, Segment Tree, Array +2
2940Find Building Where Alice and Bob Can MeetHardStack, Binary Indexed Tree, Segment Tree +4
2941Maximum GCD-Sum of a SubarrayPremiumHardArray, Math, Binary Search +1
2945Find Maximum Non-decreasing Array LengthHardStack, Queue, Array +4
2968Apply Operations to Maximize Frequency ScoreHardArray, Binary Search, Prefix Sum +2
2972Count the Number of Incremovable Subarrays IIHardArray, Two Pointers, Binary Search

Related patterns

Problems sit in more than one pattern more often than not, and the overlap is where the interesting follow-up questions live.

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.

Meet the binary search problem you did not practise

Stealth Interview is a desktop app for macOS and Windows. It reads the coding 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 is saying — while staying invisible to screen sharing.