Stage 1 · Code
Stack & Binary Search
Stack + Binary Search Drills
Mixed practice problems that combine monotonic stack reasoning with binary search optimization — two patterns that complement each other.
The Pattern
Monotonic stacks excel at finding the next greater or smaller element in O(n). Binary search on answer finds optimal numeric bounds in O(log range × n). They seem unrelated — yet they pair naturally when a problem requires both position tracking (stack) and value optimization (binary search).
Common combinations include: using a stack to compute ranges or histograms (next smaller element), then using binary search over those ranges; or using a stack to maintain candidates and binary search to query them (e.g., the 132 pattern where a stack tracks potential '3' values while binary search checks for a '2' between '1' and '3').
Temperatures stack (value→next greater)
When a problem involves 'find the minimum of maximums' over subarrays defined by next-smaller-element boundaries, the stack computes the boundaries and binary search on answer tests the feasibility. The same pattern appears in histograms, rain water, and subarray minimums.
Template
When combining stack and binary search, follow this general approach:
- Identify the decision variable: what numeric bound are we binary searching over? (e.g., capacity, speed, largest sum)
- Compute structural info with a stack: precompute next-smaller or next-greater element indices in O(n).
- Use the structural info in feasibility: the precomputed ranges let you evaluate a candidate answer faster, or let you reason about subarray properties.
- Binary search over the answer: use the standard search-on-answer template with feasibility derived from the stack's output.
Problems
Mark this lesson complete to store local progress and unlock a cleaner resume path the next time you visit.