Part 11•Chapter 3 of 9•Advanced
Hashing & Binary Search (80 Problems)
80 problems mastering hash tables, frequency counters, prefix hash lookups, and binary search on monotonic answer spaces.
~31 min read
6,190 words
5 Sections
Reviewed & Verified (2024 Syllabus)
80 Solved ProblemsBinary Search on Answer RangeHash Map Sliding Window
Constant-time dictionary lookups and logarithmic divide-and-conquer searches represent the primary mechanisms for eliminating exhaustive linear scans in software systems. This volume curates 80 foundational interview problems spanning hash table invariants, prefix sum modulo arithmetic, randomized data structures, and binary search over discrete answer spaces.
1. Executive Summary & Learning Objectives
#This problem bank codifies 80 essential challenges exploring associative table mappings and logarithmic domain reductions.
By completing this problem set, you will be able to:
- Formulate Hash Table Invariants: Exploit prefix sum complements, remainder modular arithmetic, and geometric hash representations in time.
- Design Amortized Containers: Combine dynamic arrays and hash maps to support insert, delete, and uniform random sampling in constant time.
- Partition Non-Monotonic Spaces: Execute modified binary searches across rotated sorted arrays, mountain arrays, and unknown-length streams in time.
- Binary Search on Continuous & Discrete Answer Spaces: Formulate monotonic feasibility predicates to optimize capacity allocation, scheduling, and geometric bounds.
2. Problem Taxonomy & Architecture Guide
#| Section | Problem Range | Primary Patterns Covered | Target Complexity Range |
|---|---|---|---|
| Section 1 | Q161 – Q200 | Hashing, HashMaps & Frequency Tables | Time, Space |
| Section 2 | Q201 – Q240 | Binary Search, Rotations & Answer Space Pruning | to Time, Space |
Section 1: Hashing, HashMaps & Frequency Tables (Q161 – Q200)
#Q161: Longest Consecutive Sequence
- Difficulty:
[Medium]| Pattern:[Hash Set Sequence Start] - Statement: Find length of longest consecutive elements sequence in unsorted array in time.
- Optimal Approach: Insert all numbers into a hash set. Only begin counting if is NOT in set (ensures we only start at sequence heads).
- Complexity: Time: | Space:
- Edge Cases: Empty array (length 0), large duplicate values.
Q162: Contiguous Array
- Difficulty:
[Medium]| Pattern:[Prefix Sum Hash Map with -1/1] - Statement: Find maximum length of contiguous subarray with equal number of 0s and 1s.
- Optimal Approach: Treat 0 as and 1 as . Running prefix sum . Map stores
{P: earliestIndex}. If same sum seen again, length is . - Complexity: Time: | Space:
- Edge Cases: Array with all 0s or all 1s (returns 0).
Q163: Insert Delete GetRandom O(1)
- Difficulty:
[Medium]| Pattern:[Dynamic Array + Hash Map] - Statement: Design a data structure supporting average
insert,remove, andgetRandom. - Optimal Approach: Array stores elements. Hash map stores
{val: indexInArray}. On removal, swap target with last element of array and pop back. - Complexity: Time: average all ops | Space:
- Edge Cases: Removing the last element, inserting already existing element.
Q164: Insert Delete GetRandom O(1) - Duplicates Allowed
- Difficulty:
[Hard]| Pattern:[Array + Hash Map of Index Sets] - Statement: Support average
insert,remove, andgetRandomwhen duplicates are permitted. - Optimal Approach: Map stores
{val: Set of indices}. On removal, take an index from set, swap with last element of array, update last element's index in map. - Complexity: Time: average | Space:
- Edge Cases: Removing an element when multiple copies exist.
Q165: Design Twitter
- Difficulty:
[Medium]| Pattern:[Hash Map + Priority Queue / Merge K Lists] - Statement: Support posting tweets, following/unfollowing, and generating top 10 most recent news feed tweets.
- Optimal Approach: User map with
{userId: Set of followees}. Each user maintains linked list of tweets with timestamp. Feed uses min-heap to merge k lists. - Complexity: Post: | Feed: where is followees count | Space:
- Edge Cases: Unfollowing self (disallowed), user with no tweets.
Q166: First Missing Positive
- Difficulty:
[Hard]| Pattern:[In-Place Bucket Index Placement] - Statement: Find smallest missing positive integer in time and auxiliary space.
- Optimal Approach: While and , swap to its target index . First index where is the answer.
- Complexity: Time: | Space:
- Edge Cases: All numbers present (answer ), negative numbers and zeroes.
Q167: Valid Sudoku
- Difficulty:
[Medium]| Pattern:[Hash Set Coordinate Encoding] - Statement: Determine if Sudoku board is valid according to row, column, and box rules.
- Optimal Approach: For each filled cell with value , check set for
"r" + r + v,"c" + c + v, and"b" + (r/3) + (c/3) + v. - Complexity: Time: | Space:
- Edge Cases: Empty board (valid), duplicate in same subgrid.
Q168: Bulls and Cows
- Difficulty:
[Medium]| Pattern:[Single Array Frequency Count] - Statement: Count bulls (correct digit and position) and cows (correct digit, wrong position).
- Optimal Approach: If , bull. Else, track frequencies: if count for secret digit , cow; if count for guess digit , cow.
- Complexity: Time: | Space:
- Edge Cases: Digits repeated in guess more times than in secret.
Q169: Isomorphic Strings
- Difficulty:
[Easy]| Pattern:[Dual Array Character Mapping] - Statement: Check if characters in can be replaced to get with 1-to-1 correspondence.
- Optimal Approach: Two arrays of size 256 recording last seen indices of characters in and . Indices must match at every position.
- Complexity: Time: | Space:
- Edge Cases: Two distinct characters in mapping to the same character in .
Q170: Minimum Area Rectangle
- Difficulty:
[Medium]| Pattern:[Hash Set Diagonal Point Matching] - Statement: Find minimum area of rectangle with sides parallel to axes formed from points array.
- Optimal Approach: Store points in hash set. For every pair of points and forming diagonal, check if and exist in set.
- Complexity: Time: | Space:
- Edge Cases: Points lying on the same horizontal or vertical line (cannot form diagonal).
Q171: Max Points on a Line
- Difficulty:
[Hard]| Pattern:[GCD Normalized Slope Hash Map] - Statement: Find maximum number of points that lie on the same straight line.
- Optimal Approach: For each point , calculate slopes to all other points . Represent slope as coprime pair using GCD to avoid floating point inaccuracies.
- Complexity: Time: | Space:
- Edge Cases: Vertical lines (), duplicate points.
Q172: Fraction to Recurring Decimal
- Difficulty:
[Medium]| Pattern:[Remainder Hash Map for Cycles] - Statement: Convert numerator/denominator to string, enclosing recurring decimals in parentheses.
- Optimal Approach: Perform long division. Map stores
{remainder: indexInResult}. If a remainder repeats, insert(at stored index and)at end. - Complexity: Time: | Space:
- Edge Cases: Negative results, integer overflow on
-2147483648 / -1(use 64-bit int).
Q173: Logger Rate Limiter
- Difficulty:
[Easy]| Pattern:[Hash Map Timestamp Filtering] - Statement: Return
trueif message should be printed (not printed within last 10 seconds). - Optimal Approach: Map stores
{message: nextAllowedTimestamp}. If , update map and returntrue. - Complexity: Time: | Space:
- Edge Cases: Simultaneous messages at same timestamp.
Q174: Brick Wall
- Difficulty:
[Medium]| Pattern:[Prefix Sum Hash Map Edges] - Statement: Draw vertical line crossing fewest bricks.
- Optimal Approach: Find vertical line with the most brick edges! Hash map stores
{edgePosition: count}. Result isrows - maxEdges. - Complexity: Time: | Space:
- Edge Cases: Wall where no interior edges align (line must cut all bricks).
Q175: Subdomain Visit Count
- Difficulty:
[Medium]| Pattern:[String Suffix Parsing + Map] - Statement: Count total visits for each subdomain given count-paired domains.
- Optimal Approach: For each domain
"900 google.mail.com", split count and domain. Add count to map for"google.mail.com","mail.com", and"com". - Complexity: Time: | Space:
- Edge Cases: Top-level domains with multiple suffixes.
Q176: Hand of Straights
- Difficulty:
[Medium]| Pattern:[Sorted Map Greedy Grouping] - Statement: Rearrange hand into groups of size containing consecutive cards.
- Optimal Approach: Count frequencies in sorted map. While map non-empty, take smallest key , and decrement count for .
- Complexity: Time: | Space:
- Edge Cases: Array length not divisible by .
Q177: My Calendar I
- Difficulty:
[Medium]| Pattern:[Sorted Map Floor/Ceiling Lookup] - Statement: Implement
book(start, end)without double-booking. - Optimal Approach: Store intervals in balanced BST (e.g.
TreeMap). Check ifprev.end <= startandnext.start >= end. - Complexity: Time: per booking | Space:
- Edge Cases: Booking abutting existing interval (
[10, 20)and[20, 30)).
Q178: My Calendar II
- Difficulty:
[Medium]| Pattern:[Double Booking Interval List] - Statement: Allow double-bookings, but no triple-bookings.
- Optimal Approach: Maintain
bookingsandoverlaps. New interval must not intersect any interval inoverlaps. - Complexity: Time: per booking | Space:
- Edge Cases: Overlaps of length 0.
Q179: My Calendar III
- Difficulty:
[Hard]| Pattern:[Sweep-Line Difference Map] - Statement: Return maximum -booking (max overlapping intervals at any point in time).
- Optimal Approach: Map stores delta events:
map[start]++,map[end]--. Take running prefix sum of map entries to find peak active bookings. - Complexity: Time: per booking | Space:
- Edge Cases: Multiple intervals starting/ending at exact same timestamp.
Q180: Encode and Decode TinyURL
- Difficulty:
[Medium]| Pattern:[Bi-Directional Hash Map with Counter/Hash] - Statement: Design a URL shortening service.
- Optimal Approach: Maintain two maps:
urlToShortandshortToUrl. Generate 6-character Base62 string ([a-zA-Z0-9]) from auto-incrementing counter. - Complexity: Time: | Space:
- Edge Cases: Encoding same long URL multiple times (returns same short URL).
Q181: Repeated DNA Sequences
- Difficulty:
[Medium]| Pattern:[Rolling Hash / 20-bit Bitmask] - Statement: Find all 10-letter substrings that occur more than once in DNA string.
- Optimal Approach: Encode A, C, G, T as 2-bit numbers (). A 10-letter sequence fits inside a 20-bit integer! Use rolling bitmask and hash set.
- Complexity: Time: | Space:
- Edge Cases: String length .
Q182: Rabin-Karp String Matching
- Difficulty:
[Medium]| Pattern:[Polynomial Rolling Hash] - Statement: Find all occurrences of pattern in text in expected time.
- Optimal Approach: Compute hash of pattern and initial window of text using polynomial hash . Slide window in .
- Complexity: Time: average | Space:
- Edge Cases: Hash collisions (verify actual string match when hashes match).
Q183: Longest Duplicate Substring
- Difficulty:
[Hard]| Pattern:[Binary Search on Length + Rabin-Karp] - Statement: Find longest duplicated substring in a string.
- Optimal Approach: Binary search on length . For a fixed , check if any duplicate exists using Rabin-Karp rolling hash with double modulo.
- Complexity: Time: | Space:
- Edge Cases: No duplicate substring exists (returns
"").
Q184: Snapshot Array
- Difficulty:
[Medium]| Pattern:[Array of History Lists + Binary Search] - Statement: Support
set(index, val),snap(), andget(index, snap_id). - Optimal Approach: Each array index stores a list of pairs
(snap_id, val).getuses binary search on snap_id in the target index's history list. - Complexity: Set: | Snap: | Get: | Space:
- Edge Cases: Querying
snap_idthat had no writes at that index.
Q185: Time Based Key-Value Store
- Difficulty:
[Medium]| Pattern:[Hash Map of Sorted Timestamp Arrays] - Statement: Store
{key, value, timestamp}and retrieve value attimestamp_prev <= timestamp. - Optimal Approach: Map
key -> List of (timestamp, value). Binary search (upper_bound - 1) on timestamps list to find largest timestamp . - Complexity: Set: | Get: | Space:
- Edge Cases: Target timestamp is strictly smaller than the earliest entry.
Q186: Design Underground System
- Difficulty:
[Medium]| Pattern:[Dual Hash Maps for Check-In & Travel Time] - Statement: Track customer check-ins and compute average travel times between stations.
- Optimal Approach:
checkInMap: id -> (station, time).travelMap: (start, end) -> (totalTime, tripCount). - Complexity: Time: all ops | Space:
- Edge Cases: Stations with long names, multiple users traveling simultaneously.
Q187: Finding Pairs With a Certain Sum
- Difficulty:
[Medium]| Pattern:[Hash Map Frequency Counting] - Statement: Add to
nums2and count pairs where . - Optimal Approach: Hash map of frequencies for
nums2. For each innums1, add to answer. - Complexity: Add: | Count: | Space:
- Edge Cases: Negative sums, target not attainable.
Q188: Detect Squares
- Difficulty:
[Medium]| Pattern:[Coordinate Point Counting] - Statement: Add points and count axis-aligned squares that can be formed with query point.
- Optimal Approach: For query point , iterate through all points having same coordinate (). Side length is . Check points at and .
- Complexity: Add: | Count: | Space:
- Edge Cases: Zero area squares ().
Q189: Line Reflection
- Difficulty:
[Medium]| Pattern:[Hash Set Coordinate Symmetry] - Statement: Find if there exists a vertical line that reflects all given 2D points.
- Optimal Approach: Reflection line must be . For every point , must exist in point set.
- Complexity: Time: | Space:
- Edge Cases: All points lie on the reflection line itself.
Q190: Minimum Operations to Make Array Equal
- Difficulty:
[Medium]| Pattern:[Mathematical Median] - Statement: Array . In one op, subtract 1 from one element and add 1 to another. Equalize all elements.
- Optimal Approach: Target value is average . Operations required is .
- Complexity: Time: | Space:
- Edge Cases: Even vs odd .
Q191: Alert Using Same Key-Card Three or More Times in a One Hour Period
- Difficulty:
[Medium]| Pattern:[Map of Times + Sorting Window] - Statement: Find employees with 3+ accesses within any 60-minute window.
- Optimal Approach: Map
name -> List of access minutes. Sort each list. Check iftimes[i] - times[i-2] <= 60. - Complexity: Time: | Space:
- Edge Cases: Accesses spanning midnight (guaranteed within same day).
Q192: Simple Bank System
- Difficulty:
[Medium]| Pattern:[Array State Validation] - Statement: Validate and execute bank transfers, deposits, and withdrawals.
- Optimal Approach: Array storing balances. Verify 1-based account indices are valid and balances sufficient before mutation.
- Complexity: Time: all ops | Space:
- Edge Cases: Transferring to non-existent account, insufficient funds.
Q193: Design Authentication Manager
- Difficulty:
[Medium]| Pattern:[Hash Map Expiration Times] - Statement: Manage tokens with time-to-live (), renewals, and count unexpired tokens.
- Optimal Approach: Map
tokenId -> expiryTime. On renewal, if , update expiry. Count by filtering. - Complexity: Generate/Renew: | Count: | Space:
- Edge Cases: Renewing already expired token (ignored).
Q194: Find All People With Secret
- Difficulty:
[Hard]| Pattern:[Time-Grouped BFS / DSU with Rollback] - Statement: People share secrets in meetings at specific timestamps.
- Optimal Approach: Group meetings by timestamp. Within each timestamp, construct graph between meeting participants. Run BFS from people who already know secret.
- Complexity: Time: | Space:
- Edge Cases: Multiple meetings at same timestamp forming connected components.
Q195: Count Nice Pairs in an Array
- Difficulty:
[Medium]| Pattern:[Algebraic Rearrangement Hash Map] - Statement: Count pairs where .
- Optimal Approach: Rearrange equation: . Hash map counts frequencies of .
- Complexity: Time: | Space:
- Edge Cases: Leading zeroes in reversed numbers (e.g. ).
Q196: Number of Good Ways to Split a String
- Difficulty:
[Medium]| Pattern:[Prefix & Suffix Unique Counts] - Statement: Split string into two non-empty strings with equal number of distinct characters.
- Optimal Approach: Precompute prefix count of distinct characters and suffix count. Compare at each split point.
- Complexity: Time: | Space: or
- Edge Cases: All characters identical (split everywhere valid).
Q197: Minimum Number of Pushes to Type Word II
- Difficulty:
[Medium]| Pattern:[Greedy Frequency Assignment] - Statement: Map 26 characters to 8 phone keys (2–9) to minimize total keypresses.
- Optimal Approach: Count character frequencies and sort descending. Assign top 8 to cost 1, next 8 to cost 2, next 8 to cost 3, remaining 2 to cost 4.
- Complexity: Time: | Space:
- Edge Cases: Short words with distinct characters.
Q198: Find Players With Zero or One Losses
- Difficulty:
[Medium]| Pattern:[Loss Counter Hash Map] - Statement: Return players who have lost 0 matches and players who have lost exactly 1 match.
- Optimal Approach: Hash map tracking loss count for every player seen in matches. Extract and sort players with count 0 and count 1.
- Complexity: Time: | Space:
- Edge Cases: Players who won matches but never lost.
Q199: Subarrays with K Different Integers
- Difficulty:
[Hard]| Pattern:[Sliding Window Frequency Hash Map] - Statement: Count contiguous subarrays with exactly different integers.
- Optimal Approach: Compute
atMost(k) - atMost(k - 1)using sliding window with frequency map. - Complexity: Time: | Space:
- Edge Cases: .
Q200: Minimum Deletions to Make String K-Special
- Difficulty:
[Medium]| Pattern:[Frequency Sorting] - Statement: Make max character frequency and min character frequency differ by at most .
- Optimal Approach: Count frequencies, sort. Try each frequency as target minimum: frequencies deleted completely, frequencies reduced to .
- Complexity: Time: | Space:
- Edge Cases: , all characters already equal.
Section 2: Binary Search, Bounds & Search Spaces (Q201 – Q240)
#Q201: Binary Search
- Difficulty:
[Easy]| Pattern:[Classical Sorted Search] - Statement: Search
targetin sorted array; return index or . - Optimal Approach:
low = 0, high = n - 1. Whilelow <= high,mid = low + (high - low) / 2. Narrow search half based on comparison. - Complexity: Time: | Space:
- Edge Cases: Target smaller than first element or larger than last element.
Q202: Search Insert Position
- Difficulty:
[Easy]| Pattern:[Lower Bound Binary Search] - Statement: Return index where
targetis found, or index where it would be inserted in order. - Optimal Approach: Lower bound: find smallest index such that . When loop terminates,
lowis insertion position. - Complexity: Time: | Space:
- Edge Cases: Target smaller than all elements (index 0), target larger than all (index ).
Q203: Find First and Last Position of Element in Sorted Array
- Difficulty:
[Medium]| Pattern:[Lower & Upper Bound] - Statement: Find starting and ending position of
targetin time. - Optimal Approach: Find Lower Bound () for start index. Find Upper Bound () minus 1 for end index.
- Complexity: Time: | Space:
- Edge Cases: Target not in array (returns
[-1, -1]), single element matching target.
Q204: Search in Rotated Sorted Array
- Difficulty:
[Medium]| Pattern:[Rotated Binary Search (Distinct)] - Statement: Search target in rotated sorted array of distinct values.
- Optimal Approach: At least one half ( or ) is always normally sorted! Check if target lies within the sorted half; if so, search there, else search other half.
- Complexity: Time: | Space:
- Edge Cases: Array rotated 0 times (unrotated).
Q205: Search in Rotated Sorted Array II
- Difficulty:
[Medium]| Pattern:[Rotated Binary Search with Duplicates] - Statement: Search target in rotated sorted array that may contain duplicates.
- Optimal Approach: When , cannot determine which half is sorted! Shrink search space:
low++,high--. - Complexity: Time: average, worst-case | Space:
- Edge Cases: Array of all identical elements except target
[1, 1, 1, 2, 1].
Q206: Find Minimum in Rotated Sorted Array
- Difficulty:
[Medium]| Pattern:[Inflection Point Binary Search] - Statement: Find minimum element in rotated sorted array of unique elements.
- Optimal Approach: Compare with . If , minimum is strictly in right half (
low = mid + 1); else in left half (high = mid). - Complexity: Time: | Space:
- Edge Cases: Array not rotated ( is minimum).
Q207: Find Minimum in Rotated Sorted Array II
- Difficulty:
[Hard]| Pattern:[Inflection Point with Duplicates] - Statement: Find minimum in rotated sorted array containing duplicates.
- Optimal Approach: If , decrement
high--safely. - Complexity: Time: average, worst-case | Space:
- Edge Cases:
[2, 2, 2, 0, 2, 2].
Q208: Find Peak Element
- Difficulty:
[Medium]| Pattern:[Slope Binary Search] - Statement: Find peak element in time.
- Optimal Approach: If , an upward slope guarantees a peak to the right (
low = mid + 1); else a peak exists to the left (high = mid). - Complexity: Time: | Space:
- Edge Cases: Peak at index 0, peak at index .
Q209: Peak Index in a Mountain Array
- Difficulty:
[Medium]| Pattern:[Binary Search on Mountain Slope] - Statement: Return index of peak in guaranteed mountain array.
- Optimal Approach: Binary search: if ,
low = mid + 1; elsehigh = mid. - Complexity: Time: | Space:
- Edge Cases: Length 3 (minimal mountain).
Q210: Single Element in a Sorted Array
- Difficulty:
[Medium]| Pattern:[Index Parity Binary Search] - Statement: Array where every element appears twice except one. Find it in time and space.
- Optimal Approach: Pairs before the single element start on even indices (). Binary search
mid: ensuremidis even (mid ^= 1). If , single element is to the right. - Complexity: Time: | Space:
- Edge Cases: Single element at index 0, single element at index .
Q211: Median of Two Sorted Arrays
- Difficulty:
[Hard]| Pattern:[Dual Array Partition Binary Search] - Statement: Find median of two sorted arrays in time.
- Optimal Approach: Binary search partition cut in smaller array . Compute cut in such that left half has elements. Valid if and .
- Complexity: Time: | Space:
- Edge Cases: One array empty, non-overlapping arrays.
Q212: Kth Smallest Element in a Sorted Matrix
- Difficulty:
[Medium]| Pattern:[Binary Search on Matrix Value Range] - Statement: Find -th smallest element in matrix where rows and columns are sorted.
- Optimal Approach: Binary search range . Count elements in time using staircase walk from bottom-left.
- Complexity: Time: | Space:
- Edge Cases: , .
Q213: Search a 2D Matrix
- Difficulty:
[Medium]| Pattern:[Flattened Coordinate Binary Search] - Statement: Search target in matrix where first integer of each row is greater than last integer of previous row.
- Optimal Approach: Treat as virtual 1D array of size . Coordinate mapping:
row = mid / N, col = mid % N. Standard binary search. - Complexity: Time: | Space:
- Edge Cases: Matrix with 1 row or 1 column.
Q214: Search a 2D Matrix II
- Difficulty:
[Medium]| Pattern:[Staircase Search from Corner] - Statement: Search target in matrix where rows and columns are individually sorted.
- Optimal Approach: Start at top-right corner . If , move left (
col--); if , move down (row++). - Complexity: Time: | Space:
- Edge Cases: Target smaller than minimum or larger than maximum.
Q215: Koko Eating Bananas
- Difficulty:
[Medium]| Pattern:[BS on Answer Space] - Statement: Find minimum eating speed to finish all bananas within hours.
- Optimal Approach: Binary search speed . Hours needed at speed is . If , try smaller speed (
high = mid); elselow = mid + 1. - Complexity: Time: | Space:
- Edge Cases: (speed must equal ).
Q216: Capacity to Ship Packages Within D Days
- Difficulty:
[Medium]| Pattern:[BS on Answer Space] - Statement: Find least ship capacity to ship packages within .
- Optimal Approach: Binary search capacity in . Greedy check: count days needed by accumulating weights until capacity exceeded.
- Complexity: Time: | Space:
- Edge Cases: (capacity is ), (capacity is ).
Q217: Split Array Largest Sum
- Difficulty:
[Hard]| Pattern:[BS on Answer Space] - Statement: Split array into non-empty subarrays minimizing the largest subarray sum.
- Optimal Approach: Binary search max sum in range . Greedy check: count subarrays needed to keep sums . If , valid.
- Complexity: Time: | Space:
- Edge Cases: , .
Q218: Painter's Partition Problem
- Difficulty:
[Hard]| Pattern:[BS on Answer Space] - Statement: Partition boards among painters minimizing maximum time taken.
- Optimal Approach: Identical to Split Array Largest Sum. Binary search on maximum board length painted by any single painter.
- Complexity: Time: | Space:
- Edge Cases: (each painter paints 1 board, answer is ).
Q219: Magnetic Force Between Two Balls / Aggressive Cows
- Difficulty:
[Medium]| Pattern:[BS on Answer Space (Maximize Minimum)] - Statement: Place balls in baskets maximizing minimum distance between any two balls.
- Optimal Approach: Sort basket positions. Binary search distance . Greedily place balls at first position .
- Complexity: Time: | Space:
- Edge Cases: (place at endpoints).
Q220: Minimum Speed to Arrive on Time
- Difficulty:
[Medium]| Pattern:[BS on Answer Space with Floating Point] - Statement: Find minimum integer speed to arrive in hours (trains depart on integer hours except last).
- Optimal Approach: Binary search speed . Time is .
- Complexity: Time: | Space:
- Edge Cases: (impossible, returns ).
Q221: Maximum Candies Allocated to K Children
- Difficulty:
[Medium]| Pattern:[BS on Answer Space] - Statement: Maximize candies each of children receives (piles can be divided but not merged).
- Optimal Approach: Binary search candies . Count children satisfied: .
- Complexity: Time: | Space:
- Edge Cases: Total candies (returns 0).
Q222: Minimize Max Distance to Gas Station
- Difficulty:
[Hard]| Pattern:[Floating Point Binary Search on Answer] - Statement: Add gas stations to minimize maximum distance between adjacent stations.
- Optimal Approach: Binary search distance with precision . Stations needed is .
- Complexity: Time: | Space:
- Edge Cases: Precision termination
high - low > 1e-6.
Q223: Find K Closest Elements
- Difficulty:
[Medium]| Pattern:[Binary Search on Window Start] - Statement: Find closest integers to in sorted array.
- Optimal Approach: Binary search window start index . Compare distances: if , move right (
low = mid + 1); elsehigh = mid. - Complexity: Time: | Space: auxiliary
- Edge Cases: smaller than all elements, larger than all elements.
Q224: Sqrt(x)
- Difficulty:
[Easy]| Pattern:[Integer Binary Search] - Statement: Compute without built-in exponents.
- Optimal Approach: Range . If and , return . (Avoid overflow with division).
- Complexity: Time: | Space:
- Edge Cases: .
Q225: Valid Perfect Square
- Difficulty:
[Easy]| Pattern:[Integer Binary Search] - Statement: Return
trueif num is perfect square withoutsqrt(). - Optimal Approach: Binary search range . Check if .
- Complexity: Time: | Space:
- Edge Cases: .
Q226: Arrange Coins
- Difficulty:
[Easy]| Pattern:[Binary Search on Triangular Numbers] - Statement: Find number of complete staircase rows built with coins.
- Optimal Approach: Binary search : condition . Or closed-form math: .
- Complexity: Time: math or BS | Space:
- Edge Cases: Large causing integer overflow in .
Q227: First Bad Version
- Difficulty:
[Easy]| Pattern:[Lower Bound Binary Search] - Statement: Given API
isBadVersion(version), find first bad version minimizing API calls. - Optimal Approach: Binary search range . If
isBadVersion(mid)is true,high = mid; elselow = mid + 1. - Complexity: Time: | Space:
- Edge Cases: Version 1 is already bad.
Q228: Missing Number in Sorted Array
- Difficulty:
[Easy]| Pattern:[Index Discrepancy Binary Search] - Statement: Given sorted array of arithmetic progression with one missing number, find it.
- Optimal Approach: Compare with expected value . If matches, missing number is in right half.
- Complexity: Time: | Space:
- Edge Cases: Missing number in first gap.
Q229: Count Negative Numbers in a Sorted Matrix
- Difficulty:
[Easy]| Pattern:[Staircase Matrix Walk] - Statement: Count negative numbers in matrix sorted non-increasingly row-wise and column-wise.
- Optimal Approach: Start at bottom-left corner . If cell is negative, all cells to right in this row are negative: add ,
row--; elsecol++. - Complexity: Time: | Space:
- Edge Cases: All negative, all positive.
Q230: Sum of Mutated Array Closest to Target
- Difficulty:
[Medium]| Pattern:[BS on Cap Value] - Statement: Choose integer
valuesuch that replacing elements withvaluemakes sum closest to target. - Optimal Approach: Binary search
valuein . Calculate capped sum and choose value minimizing difference to target. - Complexity: Time: | Space:
- Edge Cases: Multiple values give same difference (return smaller value).
Q231: Minimum Number of Days to Make m Bouquets
- Difficulty:
[Medium]| Pattern:[BS on Answer Space] - Statement: Bloom days array. Make bouquets of adjacent flowers. Find min day.
- Optimal Approach: Binary search day in . Greedily count adjacent flowers bloomed by day .
- Complexity: Time: | Space:
- Edge Cases: (impossible, returns ).
Q232: Cutting Ribbons
- Difficulty:
[Medium]| Pattern:[BS on Answer Space] - Statement: Cut ribbons into at least pieces of equal integer length. Maximize length.
- Optimal Approach: Binary search length . Count pieces: .
- Complexity: Time: | Space:
- Edge Cases: Total length (returns 0).
Q233: Maximum Running Time of N Computers
- Difficulty:
[Hard]| Pattern:[BS on Answer with Battery Cap] - Statement: Run computers simultaneously for minutes using batteries. Maximize .
- Optimal Approach: Binary search time . A battery with charge can contribute at most minutes. Valid if .
- Complexity: Time: | Space:
- Edge Cases: Large batteries with charge exceeding .
Q234: Minimum Limit of Balls in a Bag
- Difficulty:
[Medium]| Pattern:[BS on Max Bag Size] - Statement: Divide bags of balls in at most operations to minimize max bag size.
- Optimal Approach: Binary search penalty . Operations needed is .
- Complexity: Time: | Space:
- Edge Cases: .
Q235: Online Election
- Difficulty:
[Medium]| Pattern:[Precomputed Leaders + Binary Search] - Statement: Query candidate leading vote at timestamp .
- Optimal Approach: Precompute leader at each vote timestamp. Query uses binary search (
upper_bound - 1) on vote times to find latest leader. - Complexity: Preprocess: | Query: | Space:
- Edge Cases: Tie in votes (most recent vote breaks tie).
Q236: Russian Doll Envelopes
- Difficulty:
[Hard]| Pattern:[Sort + 1D LIS via Patience Sorting] - Statement: Find maximum envelopes you can Russian doll (fit inside one another).
- Optimal Approach: Sort envelopes: ascending width, and descending height for ties! Extract heights; find Longest Increasing Subsequence using binary search.
- Complexity: Time: | Space:
- Edge Cases: Envelopes with identical widths (descending sort on height prevents nesting identical widths).
Q237: Longest Increasing Subsequence
- Difficulty:
[Medium]| Pattern:[Patience Sorting with Binary Search] - Statement: Find length of longest strictly increasing subsequence in time.
- Optimal Approach: Maintain
tailsarray wheretails[i]is smallest tail of all increasing subsequences of length . For each , binary search (lower_bound) intailsand update/append. - Complexity: Time: | Space:
- Edge Cases: Strictly decreasing array (length 1), all elements equal.
Q238: Find in Mountain Array
- Difficulty:
[Hard]| Pattern:[Triple Binary Search] - Statement: Find target in
MountainArraywith calls toget(). - Optimal Approach: 1. BS to find peak index. 2. BS on ascending left slope. 3. If not found, BS on descending right slope.
- Complexity: Time: | Space:
- Edge Cases: Target at peak, target present on both slopes (must return smaller index).
Q239: Heaters
- Difficulty:
[Medium]| Pattern:[Binary Search Nearest Neighbor] - Statement: Find minimum radius for heaters to warm all houses.
- Optimal Approach: Sort heaters. For each house, binary search closest heater to left and right. Radius is .
- Complexity: Time: | Space: auxiliary
- Edge Cases: All heaters to one side of all houses.
Q240: Guess Number Higher or Lower
- Difficulty:
[Easy]| Pattern:[Interactive Binary Search] - Statement: Guess number using
guess(num)feedback (). - Optimal Approach: Standard binary search. Midpoint calculation to prevent integer overflow.
- Complexity: Time: | Space:
- Edge Cases: Number is 1 or .
References & Academic Attribution
#- Skiena, S. S. (2020). The Algorithm Design Manual (3rd ed.). Springer.
- Cormen, T. H., Leiserson, C. E., Rivest, R. L., & Stein, C. (2022). Introduction to Algorithms (4th ed.). MIT Press.
- USA Computing Olympiad (USACO) & CP-Algorithms Archives (2024). Curated Competitive Programming and Algorithm Verification Standards.