When choosing between sliding window, heap, binary search on answer, or DP, verify the exact monotonicity or state invariant against negative numbers and duplicates.
TL;DR30-second simplified summary▾
Balance time and auxiliary space across problem families: use prefix-sum hash maps when negative numbers break sliding windows, size-K min-heaps when K << N, and monotonic predicates for binary search on answer.
Start with Constraints, Brute Force, and the Bottleneck.
Why this matters: Read input bounds to predict target time complexity and spot redundant work.
Before typing a single line of code, spend 3 minutes on constraints, complexity trade-offs, and bottlenecks:
N <= 10: permutation backtracking (O(N!)).N <= 20: subset backtracking / bitmask DP (O(2^N)orO(N * 2^N)).N <= 2,000:O(N^2)DP or nested loops.N <= 10^5:O(N log N)sorting/heap/binary search orO(N)sliding window/hash map.
State the brute-force complexity in 20 seconds, then compare intermediate and optimal options across the exact input constraints (N, value range U, negative numbers, duplicates, and auxiliary memory). For example, finding the top K elements takes O(N log N) with full sorting, O(N log K) with a size-K min-heap (better when K << N or streaming), and O(N) expected time with Quickselect or O(N + U) with bucket sort when frequencies are bounded by N.
Pinpoint what repeated work makes the brute force slow and state the first-principles invariant that eliminates it:
- Recomputing subarray sums -> prefix sum invariant
sum(l..r) = pref[r + 1] - pref[l]. - Scanning a window for min/max -> monotonic deque invariant (elements remain strictly ordered and within
[i - k + 1, i]). - Checking all pairs in a sorted array -> two-pointer monotonicity (moving the left pointer right can never decrease the sum).
Constraints -> Brute Force -> Bottleneck -> Invariant -> Code
Naming the invariant before typing prevents off-by-one rewrites halfway through the interview.
You are asked to find the longest contiguous subarray with sum equal to k for N = 10^5 integers where nums[i] can be negative, zero, or positive. Why does a two-pointer sliding window fail here, and what invariant fixes it?
Map Problem Structure to the 6 High-Leverage Families.
Why this matters: Cover the core coding interview problem families with crisp mental triggers and production bridges.
Focus deep mastery on the 6 families that generalize across variations:
- Sliding Window & Two Pointers: Contiguous subarrays/substrings with monotonic validity (all non-negative sums, frequency counts). In production, this same windowing logic powers streaming rate-limiters and rolling p99 metric aggregators.
- Monotonic Stack / Deque: Next greater/smaller element, histogram areas, sliding window max. Every element is pushed and popped at most once, guaranteeing
O(N)amortized work. - Binary Search on Answer: Monotonic predicate
canAchieve(mid)over capacity, time, or rate (lo= minimum feasible,hi= maximum feasible). - Heaps & Top-K / Intervals: K-way merge, scheduling, greedy sweep-line. At production scale (when
Nexceeds RAM in Kafka or Redis streams), exact Top-K heaps bridge to approximate sketches like Count-Min Sketch for heavy-hitter detection. - BFS / DFS / Topological Sort / Union-Find: Shortest unweighted paths, cycle detection, dynamic connectivity (which maps directly to network-partition and cluster-membership checks).
- Dynamic Programming: Overlapping subproblems with clear state transitions (
dp[i]meaning stated in plain English before writing loops).
# Binary Search on Answer invariant: lo..hi always contains the minimum feasible value
def min_feasible(lo: int, hi: int, can_achieve) -> int:
while lo < hi:
mid = lo + (hi - lo) // 2
if can_achieve(mid):
hi = mid # mid works; search left half including mid
else:
lo = mid + 1 # mid fails; discard mid and everything left
return loDepth on Invariants Beats Memorizing 500 Solutions
- Grinding random problems
- Blanking on slight twists
- Coding before proving invariant
- Explain why window/stack shrinks
- Prove base cases & transitions
- Dry-run edge cases cleanly
When you can explain why an invariant holds, slight problem twists stop throwing you off.
You need to find the minimum shipping capacity C to ship all packages within D days (N = 5 * 10^4 packages, weights up to 500). Why does Binary Search on Answer apply, and what must be true about canAchieve(C)?
Write Clean Code, Catch Runtime Traps, and Dry-Run Edge Cases.
Why this matters: Catch off-by-one bugs, language/runtime traps, and communicate trade-offs clearly.
Never say "I am done" the second you type the last brace. Walk through your code systematically:
- One non-trivial happy path: Trace variable values line by line on a 4–5 element example.
- Boundary inputs: Empty array, single element, all duplicates, negative numbers, disconnected graph, or skewed tree.
- Language & runtime traps (Java / Python):
- Java
intoverflow:(low + high) / 2overflows whenlow + high > Integer.MAX_VALUE; uselow + ((high - low) >>> 1). Summing10^5elements up to10^9overflows 32-bitint; uselong. Compare boxedIntegerobjects with.equals(), never==(which breaks outside the-128..127cache). - Python shared list aliasing & recursion limits:
dp = [[0] * n] * mcreatesmreferences to the same row list—mutatingdp[0][0]mutatesdp[1][0]. Always use[[0] * n for _ in range(m)]. ForN = 10^5graphs or trees, recursive DFS hits Python's default 1000-frame recursion limit (RecursionError); convert to an explicit iterative stack.
- Final complexity: State exact time and auxiliary space (including recursion stack depth).
// Safe binary search midpoint & overflow-safe prefix sum accumulation in Java
int mid = low + ((high - low) >>> 1);
long prefixSum = 0L; // avoids 32-bit int overflow when summing 10^5 * 10^9Balanced Time Allocation in a Coding Round
Agreeing on the approach before coding avoids wasting 20 minutes implementing the wrong idea.
Your Python DP solution initializes a grid with dp = [[0] * cols] * rows, and your Java binary search computes int mid = (low + high) / 2. Both pass small sample tests but fail on larger inputs. What are the two exact bugs?
Practice: Make the trade-off yourself.
An array problem has `N <= 10^5` and asks for a subarray condition. Your brute-force nested loop is `O(N^2)`. Why should you check whether negative numbers are allowed before choosing a sliding window?
How to Prepare for Coding Round
Pattern recognition is pattern-to-invariant mapping: identify what information must be remembered across steps, pick the smallest data structure that maintains it, and verify runtime traps and boundary inputs before finishing.