binary search answer space Pattern
197 problems
Pattern pages help build reusable solving frames. Identify signals first, then explain state, transition, and edge handling.
Recognition Signals
- The candidate demonstrates a clear understanding of binary search over a valid answer space.
- The candidate can explain how the partitioning logic helps in avoiding unnecessary merging of arrays.
- Ask why a standard binary search fails on rotated arrays.
Solve Flow
- 1. Define the active state/window.
- 2. Update state while preserving invariants.
- 3. Validate with edge-heavy examples.
Common Misses
- Confusing partitioning logic can lead to incorrect median calculations.
- Attempting simple binary search without handling rotation leads to incorrect indices.
- Using a single binary search and assuming the first match is the left boundary.
Recommended Ladder
Median of Two Sorted Arrays
Find the median of two sorted arrays using binary search for efficient O(log(min(m, n))) time complexity.
Search in Rotated Sorted Array
Find the index of a target in a rotated sorted array using a careful binary search that handles pivot shifts.
Find First and Last Position of Element in Sorted Array
Locate the first and last index of a target in a sorted array using binary search for precise O(log n) performance.
Search Insert Position
Find the correct index for a target value in a sorted array using binary search, or return the position where it should …
Sqrt(x)
Solve the Sqrt(x) problem using binary search to find the integer square root of a number without built-in operators.
Search a 2D Matrix
Search a 2D matrix efficiently using binary search over its linearized index, ensuring correctness in row-major sorted a…
Search in Rotated Sorted Array II
Determine if a target exists in a rotated sorted array that may contain duplicates using a binary search variation effic…
Find Minimum in Rotated Sorted Array
Find the minimum element in a rotated sorted array using binary search to efficiently identify the point of rotation.
Find Minimum in Rotated Sorted Array II
Find the minimum in a rotated sorted array with possible duplicates using binary search.
Find Peak Element
Find Peak Element leverages binary search for efficiently locating a peak in an array, a problem commonly asked in techn…
Two Sum II - Input Array Is Sorted
Solve the Two Sum II problem efficiently using binary search over a valid answer space in a sorted array.
Minimum Size Subarray Sum
Find the minimal length of a subarray whose sum is greater than or equal to the target using efficient algorithms.
Search a 2D Matrix II
Efficiently search for a target in a 2D matrix using binary search and matrix properties.
H-Index II
Compute a researcher's H-Index from a sorted citation array using binary search over the valid answer space efficiently.
First Bad Version
Find the first bad version of a product using binary search, minimizing the number of API calls.
Find the Duplicate Number
The problem involves finding the duplicate number in an array of integers, using a binary search approach over the valid…
Count of Smaller Numbers After Self
Solve the Count of Smaller Numbers After Self problem using binary search and optimized algorithms.
Count of Range Sum
Count the number of subarray sums within a given inclusive range using optimized divide-and-conquer techniques efficient…
Data Stream as Disjoint Intervals
The problem involves designing a class to summarize a data stream of non-negative integers as disjoint intervals using b…
Max Sum of Rectangle No Larger Than K
Solve the "Max Sum of Rectangle No Larger Than K" problem using binary search over the valid sum space to optimize space…
Valid Perfect Square
Determine if a given positive integer is a perfect square using a binary search approach over potential square roots eff…
Guess Number Higher or Lower
Find the picked number efficiently using binary search while adjusting guesses based on higher or lower feedback in this…
Kth Smallest Element in a Sorted Matrix
Find the kth smallest element in a sorted n x n matrix using efficient binary search or heap strategies for optimized me…
Nth Digit
Given n, efficiently find the nth digit in the infinite integer sequence using a binary search over valid positions.
Arranging Coins
Determine the maximum number of complete staircase rows possible with n coins using a binary search approach.
132 Pattern
Identify whether a given integer array contains a 132 pattern subsequence using efficient stack and search techniques.
Heaters
Determine the minimum heater radius to cover all houses using a binary search over potential radius values efficiently.
Smallest Good Base
Find the smallest good base of an integer n using binary search over the valid answer space.
Reverse Pairs
Count the number of reverse pairs in a given integer array using efficient algorithms like binary search and merge sort.
Random Point in Non-overlapping Rectangles
Design an algorithm to pick random points within non-overlapping rectangles using binary search and reservoir sampling.
Random Pick with Weight
Random Pick with Weight requires implementing a probabilistic index picker using prefix sums and binary search efficient…
Single Element in a Sorted Array
Find the single non-duplicate element in a sorted array where every other element appears exactly twice.
Valid Triangle Number
Count all triplets in an integer array that satisfy the triangle inequality to form valid triangles efficiently using so…
Sum of Square Numbers
Given a non-negative integer c, determine if there are two integers whose squares sum to c.
Find K Closest Elements
Identify the k integers closest to a target x in a sorted array using binary search and two-pointer strategies efficient…
Kth Smallest Number in Multiplication Table
Find the kth smallest number in an m x n multiplication table using binary search over the valid answer space.
Binary Search
Solve the Binary Search problem by finding the index of a target value in a sorted array with O(log n) complexity.
Subarray Product Less Than K
Count subarrays with a product strictly less than a given value k using efficient algorithms like binary search and slid…
Find K-th Smallest Pair Distance
Solve Find K-th Smallest Pair Distance by sorting nums, then binary searching the distance and counting valid pairs with…
My Calendar I
Implement a calendar supporting non-overlapping event bookings using binary search for efficient insertion and conflict …
My Calendar II
Implement a calendar that allows double bookings but prevents triple bookings, managing overlapping intervals efficientl…
My Calendar III
Implement My Calendar III to track maximum overlapping events efficiently using binary search and segment tree technique…
Find Smallest Letter Greater Than Target
Locate the smallest character in a sorted array that is strictly greater than a given target using efficient binary sear…
Reach a Number
Determine the minimum number of moves to reach a target on an infinite number line using step increments, leveraging bin…
Swim in Rising Water
Solve the problem of swimming through a grid of rising water with a binary search on the valid answer space.
K-th Smallest Prime Fraction
Find the k-th smallest fraction from a sorted array of unique primes using a binary search over the answer space.
Preimage Size of Factorial Zeroes Function
Solve for the number of integers whose factorial ends with a specific number of zeroes using binary search techniques.
Friends Of Appropriate Ages
The Friends Of Appropriate Ages problem involves counting valid friend requests between people based on their ages with …
Most Profit Assigning Work
Assign workers to jobs maximizing total profit using difficulty, profit, and worker arrays efficiently with binary searc…
Peak Index in a Mountain Array
Find the peak index in a mountain array using binary search for efficient O(log n) time complexity.
Shortest Subarray with Sum at Least K
Find the shortest subarray with a sum of at least k using binary search and sliding window techniques.
Koko Eating Bananas
Koko Eating Bananas challenges you to find the minimum eating speed to finish piles of bananas in a given time using bin…
Nth Magical Number
Find the nth magical number divisible by a or b, using binary search to efficiently handle large inputs.
Time Based Key-Value Store
Implement a time-based key-value store that retrieves the latest value at a given timestamp using efficient binary searc…
Max Consecutive Ones III
Find the longest consecutive ones in a binary array by optimally flipping at most k zeros using sliding window technique…
Capacity To Ship Packages Within D Days
Find the minimum ship capacity needed to ship all packages within D days, ensuring the cargo is shipped in the given ord…
Longest Duplicate Substring
Find the longest duplicated substring in a string using binary search, sliding window, and rolling hash techniques.
Find in Mountain Array
Find in Mountain Array requires locating a target using binary search over a peak-structured array efficiently in intera…
Online Majority Element In Subarray
Efficiently find the majority element in any subarray using a data structure optimized for multiple range queries.
Ugly Number III
Find the nth positive integer divisible by a, b, or c using binary search over the answer space efficiently and accurate…
Get Equal Substrings Within Budget
Optimize substring transformations using a binary search approach to maximize the change within a budget.
Find Positive Integer Solution for a Given Equation
Determine all positive integer pairs that satisfy a hidden monotonic function for a given target using binary search ove…
Search Suggestions System
Design a search suggestion system that provides the top three lexicographically smallest products matching a search word…
Find the Smallest Divisor Given a Threshold
Find the smallest divisor such that the sum of all divided array elements is less than or equal to the threshold.
Maximum Side Length of a Square with Sum Less than or Equal to Threshold
This problem challenges you to find the largest square in a matrix with a sum below a given threshold using binary searc…
Sum of Mutated Array Closest to Target
Find the integer that mutates all larger elements in an array to minimize the sum difference to a target efficiently.
The K Weakest Rows in a Matrix
Find the k weakest rows in a binary matrix where rows contain soldiers and civilians, using sorting and binary search te…
Tweet Counts Per Frequency
Design an efficient solution to track and retrieve tweet counts over different frequencies using binary search and hash …
Count Negative Numbers in a Sorted Matrix
Count Negative Numbers in a Sorted Matrix requires counting negative numbers in a matrix sorted in non-increasing order …
Find the Distance Value Between Two Arrays
Calculate the distance value between two integer arrays by determining how many elements in arr1 don't have a close coun…
Find the Kth Smallest Sum of a Matrix With Sorted Rows
Find the kth smallest sum in a matrix with sorted rows using binary search and a heap-based approach.
Minimum Number of Days to Make m Bouquets
Determine the minimum number of days required to make m bouquets using k adjacent flowers efficiently with binary search…
Number of Subsequences That Satisfy the Given Sum Condition
Count all non-empty subsequences in an integer array where the sum of the minimum and maximum elements is at most a targ…
Range Sum of Sorted Subarray Sums
Compute the sum of sorted subarray sums efficiently using binary search over valid sum ranges and prefix sum accumulatio…
Find a Value of a Mysterious Function Closest to Target
In this problem, you'll use binary search to find the closest value of a mysterious function to a given target.
Kth Missing Positive Number
Find the kth missing positive integer in a strictly increasing array using binary search over the answer space efficient…
Magnetic Force Between Two Balls
Maximize the minimum magnetic force between balls by strategically placing them in baskets using binary search on positi…
Shortest Subarray to be Removed to Make Array Sorted
Find the shortest subarray to remove in order to make an array non-decreasing using binary search and two-pointer techni…
Special Array With X Elements Greater Than or Equal X
Determine if an array has exactly x elements greater than or equal to x using binary search over the answer space.
Path With Minimum Effort
Find the minimum effort required to travel from the top-left to the bottom-right of a grid, considering height differenc…
Sell Diminishing-Valued Colored Balls
Maximize total value by greedily selling diminishing-valued colored balls based on inventory and customer orders.
Create Sorted Array through Instructions
The problem asks to compute the cost of inserting elements into a sorted array using a series of instructions.
Ways to Split Array Into Three Subarrays
The problem requires finding the number of ways to split an array into three subarrays where each split meets a certain …
Building Boxes
Optimize the number of boxes touching the floor in a cubic room using binary search to minimize floor occupancy.
Minimum Limit of Balls in a Bag
Find the minimum penalty (maximum balls in a bag) after performing up to maxOperations to split bags of balls.
Maximum Score of a Good Subarray
Maximize the score of a good subarray using binary search to explore the valid answer space with a focus on two-pointer …
Maximum Value at a Given Index in a Bounded Array
Maximize the value at a given index of an array with constraints using binary search over the valid answer space.
Minimum Absolute Sum Difference
Minimize the absolute sum difference between two integer arrays by replacing at most one element from the first array.
Frequency of the Most Frequent Element
Maximize the frequency of an element in an array by incrementing at most `k` elements. Use binary search and greedy tech…
Closest Room
Find the closest hotel room meeting minimum size requirements using binary search over the valid answer space efficientl…
Minimum Interval to Include Each Query
Find the smallest interval containing each query efficiently using binary search.
Maximum Distance Between a Pair of Values
Find the maximum distance between a pair of values in two non-increasing integer arrays using binary search.
Sum of Floored Pairs
The problem asks to calculate the sum of floor divisions for all pairs in a given integer array, using an efficient meth…
Minimum Speed to Arrive on Time
This problem asks to find the minimum speed of trains to reach on time using binary search.
Minimum Space Wasted From Packaging
Minimize the wasted space when packaging items into boxes, considering package and box size constraints.
Find the Student that Will Replace the Chalk
Identify the first student who will run out of chalk using a simulation with prefix sums and binary search.
Maximum Number of Removable Characters
Use binary search and a subsequence check to find the largest removable prefix that still keeps p inside s.
Find a Peak Element II
Locate any peak in a 2D matrix using binary search across rows or columns for efficient discovery and verification.
Longest Common Subpath
The Longest Common Subpath problem requires finding the longest subpath shared by all paths in a graph using binary sear…
Minimum Garden Perimeter to Collect Enough Apples
Find the minimum perimeter of a square garden that holds enough apples based on a specific formula involving binary sear…
Find the Longest Valid Obstacle Course at Each Position
Compute the longest valid obstacle course at each position using binary search and careful array tracking techniques eff…
Last Day Where You Can Still Cross
Find the last day to walk from top to bottom in a flooded matrix by using binary search and graph traversal techniques.
Maximize the Confusion of an Exam
Maximize the Confusion of an Exam requires adjusting at most k answers to create the longest consecutive true or false s…
Kth Smallest Product of Two Sorted Arrays
Find the kth smallest product from two sorted arrays using binary search across possible product values efficiently.
Plates Between Candles
Determine the number of plates between candles in a given substring using binary search and prefix sum techniques.
Minimized Maximum of Products Distributed to Any Store
Distribute products to stores so the largest store allocation is minimized using binary search over possible maximums.
Most Beautiful Item for Each Query
Determine the maximum beauty of items affordable for each query using efficient binary search and sorting techniques.
Maximum Number of Tasks You Can Assign
Maximize the number of tasks that can be completed by efficiently using workers and magical pills.
Find Target Indices After Sorting Array
Find the target indices of a sorted array and return them in increasing order using binary search and sorting techniques…
Maximum Fruits Harvested After at Most K Steps
Compute the maximum fruits collectable on an infinite line by moving at most k steps from a start position efficiently.
Minimum Operations to Make the Array K-Increasing
This problem requires finding the minimum number of operations to make an array K-increasing using binary search over th…
Maximum Running Time of N Computers
Solve the problem of determining the maximum running time of n computers using a set of batteries.
Count Good Triplets in an Array
Count Good Triplets in an Array requires tracking index orders across two permutations efficiently using binary search.
Minimum Time to Complete Trips
Find the minimum time required for buses to complete at least totalTrips using binary search over time multiples.
Sum of Scores of Built Strings
Calculate the sum of scores of built strings by analyzing longest common prefixes with suffixes in a string using effici…
Maximum Candies Allocated to K Children
Maximize candies allocation for k children by dividing piles into sub-piles using binary search.
Maximum Total Beauty of the Gardens
Determine the maximum total beauty of gardens by strategically planting flowers using binary search over achievable flow…
Escape the Spreading Fire
Maximize the time you can stay at your starting position before moving to safely reach the safehouse while avoiding fire…
Maximum White Tiles Covered by a Carpet
Solve Maximum White Tiles Covered by a Carpet by sorting intervals, checking optimal carpet starts, and counting full pl…
Booking Concert Tickets in Groups
Design a ticketing system to allocate concert seats in specific groupings while efficiently handling seat reservations.
Successful Pairs of Spells and Potions
Count how many potions pair successfully with each spell using binary search over sorted potion strengths efficiently.
Count Subarrays With Score Less Than K
Count all non-empty subarrays whose score, defined as sum times length, is strictly less than a given integer k efficien…
The Latest Time to Catch a Bus
Find the latest time to catch a bus based on departure times, passenger arrivals, and capacity using binary search over …
Minimum Sum of Squared Difference
Calculate the minimum sum of squared differences between two arrays using limited modifications and binary search techni…
Maximum Number of Groups Entering a Competition
Determine the maximum number of ordered non-empty student groups for a competition using grades array analysis and binar…
Longest Subsequence With Limited Sum
Find the maximum size of a subsequence from nums with a sum less than or equal to each query value.
Maximum Number of Robots Within Budget
Determine the maximum number of consecutive robots you can operate without exceeding a given budget using efficient bina…
Smallest Subarrays With Maximum Bitwise OR
Find the smallest subarrays with the maximum bitwise OR for each starting index in an array.
Longest Uploaded Prefix
Calculate the longest continuous uploaded prefix in a video stream efficiently using a mix of binary search and data str…
Number of Pairs Satisfying Inequality
Count pairs in two arrays satisfying a given inequality condition using binary search over the valid answer space.
Minimum Cost to Make Array Equal
Find the minimum cost to make all elements of an array equal by using binary search over valid answers.
Next Greater Element IV
Find the second greater integer for each element in an array using binary search and monotonic stack techniques.
Split Message Based on Limit
Split Message Based on Limit requires dividing a string into parts with length constraints using a calculated suffix pat…
Frog Jump II
Frog Jump II requires finding the minimal maximum jump length for a frog to traverse stones forward and backward efficie…
Minimize the Maximum of Two Arrays
Minimize the Maximum of Two Arrays requires finding the smallest possible maximum number across two arrays, using binary…
Maximum Tastiness of Candy Basket
Maximize the tastiness of a candy basket by choosing k candies from a list of candy prices.
Maximize the Minimum Powered City
Determine the maximum minimum power a city can achieve by strategically adding power stations using binary search and pr…
Maximum Count of Positive Integer and Negative Integer
Compute the maximum count between positive and negative integers in a sorted array using efficient binary search countin…
Maximize Win From Two Segments
Maximize the total prizes by choosing two segments of length k on a sorted line of prize positions efficiently using bin…
Count the Number of Fair Pairs
Efficiently count all fair pairs in an array using sorting and binary search, focusing on the sum range between lower an…
Subsequence With the Minimum Score
Find the minimum score of a string by removing characters from t while maintaining subsequence validity with s.
Find the Maximum Number of Marked Indices
Maximize marked indices in an array by performing allowed operations, applying binary search to find the optimal count e…
Minimum Time to Complete All Tasks
Determine the minimum active time for a computer to complete all scheduled tasks within their specific time windows effi…
Minimum Time to Repair Cars
Find the minimum time to repair all cars using mechanics with different ranks, applying binary search over possible time…
Prime Subtraction Operation
Determine if it's possible to make the array strictly increasing using prime subtractions.
Minimum Operations to Make All Array Elements Equal
Find the minimum number of operations to make all elements in an array equal for each query.
Make Array Empty
Solve the "Make Array Empty" problem using binary search to determine the minimum number of operations required.
Maximum Sum Queries
Find the maximum sum of paired elements from two arrays under query constraints using efficient binary search techniques…
Maximum Beauty of an Array After Applying Operation
Find the maximum beauty of an array by adjusting elements within a range using binary search and sliding window techniqu…
Maximum Number of Groups With Increasing Length
Maximize the number of groups that can be formed with given usage limits, leveraging binary search for optimal solutions…
Find the Safest Path in a Grid
Find the Safest Path in a Grid uses binary search and BFS to maximize path safeness from thieves in a grid.
Minimum Absolute Difference Between Elements With Constraint
Find the minimum absolute difference between two array elements that are at least x indices apart using binary search.
Count Pairs Whose Sum is Less than Target
This problem asks you to count all index pairs in an array whose sum is strictly less than a given target value efficien…
Maximum Number of Alloys
Determine the maximum number of alloys possible using limited metal stock and budget, leveraging binary search efficient…
Find Building Where Alice and Bob Can Meet
Determine the leftmost building where Alice and Bob can meet using a binary search over valid move sequences.
Minimum Cost to Make Array Equalindromic
Determine the minimum cost to convert an integer array into a palindromic array using allowed element modifications effi…
Apply Operations to Maximize Frequency Score
Maximize the frequency score by applying up to k operations on a sorted array using binary search over valid answer spac…
Count the Number of Incremovable Subarrays I
Count the number of incremovable subarrays in an array by removing them to create a strictly increasing sequence.
Count the Number of Incremovable Subarrays II
Count the number of incremovable subarrays where removal of the subarray results in a strictly increasing array.
Find Longest Special Substring That Occurs Thrice I
Find the longest special substring in a string that appears at least three times, or return -1 if no such substring exis…
Find Longest Special Substring That Occurs Thrice II
Find the longest special substring that occurs at least three times in a given string using binary search and hash table…
Find Beautiful Indices in the Given Array I
Identify all beautiful indices where substring a appears and a nearby substring b exists within distance k efficiently.
Find Beautiful Indices in the Given Array II
Find Beautiful Indices in the Given Array II challenges you to use binary search and string matching techniques.
Earliest Second to Mark Indices I
The problem asks to determine the earliest second to mark all indices in an array using a set of operations.
Earliest Second to Mark Indices II
This problem asks to determine the earliest second at which all indices in an array can be marked using a sequence of op…
Find the Number of Subarrays Where Boundary Elements Are Maximum
Count the subarrays where the first and last elements are the largest in the subarray, utilizing binary search over vali…
Kth Smallest Amount With Single Denomination Combination
Find the kth smallest amount using only one coin denomination at a time, applying binary search efficiently over possibl…
Find Products of Elements of Big Array
Solve queries on a massive array of powers of two using binary search to efficiently compute modular products of subarra…
Special Array II
Determine whether each subarray meets the special condition of alternating parity for all adjacent elements efficiently …
Block Placement Queries
Determine if blocks can be placed on an infinite number line using queries, leveraging binary search over the valid answ…
Find Subarray With Bitwise OR Closest to K
Find a subarray with bitwise OR closest to a given value k with minimal absolute difference.
Number of Subarrays With AND Value of K
The problem asks to find the number of subarrays with a given AND value in an array, utilizing binary search for optimiz…
Count Substrings That Satisfy K-Constraint II
Count Substrings That Satisfy K-Constraint II requires finding valid substrings in a binary string based on a k-constrai…
Maximize Score of Numbers in Ranges
Maximize Score of Numbers in Ranges asks to find the maximum score by selecting integers within given intervals with a f…
Length of the Longest Increasing Path
Determine the maximum length of an increasing path in a 2D array using binary search over potential path lengths efficie…
Minimum Number of Seconds to Make Mountain Height Zero
Determine the minimum seconds required to reduce a mountain to zero height using simultaneous workers efficiently.
Maximum Frequency of an Element After Performing Operations I
Maximize the frequency of an element in an array after performing a series of operations to find the best possible resul…
Maximum Frequency of an Element After Performing Operations II
Determine the maximum frequency of any element after performing limited operations using binary search and sliding windo…
Adjacent Increasing Subarrays Detection II
Find the largest k where two adjacent strictly increasing subarrays of length k exist using binary search techniques.
Zero Array Transformation II
Zero Array Transformation II requires determining the minimum query sequence to convert all array elements to zero using…
Minimize the Maximum Adjacent Element Difference
Minimize the maximum adjacent element difference by filling missing values with two chosen numbers.
Smallest Substring With Identical Characters I
Minimize the length of the longest substring with identical characters after at most numOps changes in a binary string.
Smallest Substring With Identical Characters II
Find the minimal length of a substring with identical characters using binary search and controlled character flips effi…
Maximum Coins From K Consecutive Bags
Solve the problem of maximizing coins from selecting k consecutive bags, using binary search and sliding window techniqu…
Maximize the Minimum Game Score
Maximizing the minimum score after at most m moves, leveraging binary search and greedy strategies over an array of scor…
Separate Squares I
Find the minimum y-coordinate of a horizontal line that balances the areas of squares above and below it.
Separate Squares II
Separate Squares II requires finding the minimum y-coordinate such that squares' areas are split evenly above and below …
Shortest Matching Substring
Find the shortest substring in a string that matches a pattern with exactly two wildcards efficiently using binary searc…
Maximize the Distance Between Points on a Square
Select k points on a square boundary to maximize minimum Manhattan distance using binary search and greedy placement str…
Fruits Into Baskets II
Determine the number of fruit types that remain unplaced after all allocations in the "Fruits Into Baskets II" problem.
Fruits Into Baskets III
Fruits Into Baskets III requires placing fruits into baskets efficiently using binary search over the answer space for c…
Maximize Active Section with Trade II
Maximize the number of active sections in a binary string with at most one trade.
Path Existence Queries in a Graph II
Solve path existence queries in a graph using binary search on the answer space, focusing on sorted nodes and maximum di…
Maximize Spanning Tree Stability with Upgrades
Maximizing the stability of a spanning tree with upgrades requires careful optimization of edge strengths using binary s…
Minimum Stability Factor of Array
The problem requires finding the minimum stability factor of an array by utilizing binary search and math-based optimiza…
Minimum Time for K Connected Components
Find the minimum time to remove edges such that a graph with n nodes has at least k connected components.
Minimize Maximum Component Cost
Minimize Maximum Component Cost leverages binary search over edge weights to optimize the cost of graph components after…