No basic loop tutorials. Master the recognition signals, real-world systems connections, and interview traps that separate strong engineers from memorized solutions.
Tier 1 · 80% Core ScreenTime: O(N)Space: O(1) to O(K)Linear Arrays & Windows
Sliding Window (Fixed & Dynamic)
HOW TO SPOT IT IN AN INTERVIEW
Finding the min, max, longest, or shortest contiguous subarray or substring.
Constraints like "at most K distinct elements", "sum >= target", or "all unique characters".
The problem statement involves a moving time or sequence window.
MENTAL MODEL & BLUEPRINT
// Dynamic window template: expand right, shrink left when invariant breaks
let left = 0, best = 0
const state = new Map()
for (let right = 0; right < arr.length; right++) {
add(arr[right], state)
while (!isValid(state)) {
remove(arr[left], state)
left++
}
best = Math.max(best, right - left + 1)
}
Where it lives in production: Powers token-bucket and rolling-window rate limiters (e.g., Cloudflare/Envoy), sliding stream telemetry in APM agents, and network packet burst detection.
Interview Trap / Pitfall: Failing to shrink the window with a while loop once the invariant is violated; applying this pattern when array elements can be negative (use Prefix Sums + Hash Map instead).
CANONICAL BENCHMARKS
Longest Substring Without Repeating CharactersMinimum Window SubstringSliding Window MaximumFruit Into Baskets
Input array is sorted (or can be sorted in O(N log N)).
Searching for pairs, triplets, or container boundaries meeting an exact target.
Reversing or partitioning sequences in-place without allocating auxiliary memory.
MENTAL MODEL & BLUEPRINT
// Converging two pointers on sorted array
let left = 0, right = arr.length - 1
while (left < right) {
const current = arr[left] + arr[right]
if (current === target) {
return [left, right]
} else if (current < target) {
left++
} else {
right--
}
}
Where it lives in production: Directly mirrors database merge-join algorithms on sorted index keys, in-memory compaction, and audio/video packet alignment in WebRTC jitter buffers.
Interview Trap / Pitfall: Infinite loops when advancing pointers; failing to skip identical values when deduplicating triplets (e.g., in 3Sum).
CANONICAL BENCHMARKS
Two Sum II (Input Array Is Sorted)3SumContainer With Most WaterTrapping Rain Water
Need to compute sum of arbitrary subarrays in O(1) after preprocessing.
"Count subarrays where sum equals K" (especially with negative numbers where sliding window fails).
Cumulative frequency, balance checks, or 2D matrix region sums.
MENTAL MODEL & BLUEPRINT
// Running prefix sum with frequency map: subarraySum(i..j) = prefix[j] - prefix[i-1]
const seen = new Map([[0, 1]]) // base case
let currentSum = 0, matches = 0
for (const num of nums) {
currentSum += num
if (seen.has(currentSum - k)) {
matches += seen.get(currentSum - k)!
}
seen.set(currentSum, (seen.get(currentSum) || 0) + 1)
}
Where it lives in production: Used in financial ledgers for point-in-time balance calculations, audit log range metrics, and time-series histogram bucketing in Prometheus.
Interview Trap / Pitfall: Forgetting to seed the running prefix hash map with { 0: 1 } to count valid subarrays that start at index 0.
CANONICAL BENCHMARKS
Subarray Sum Equals KContiguous Array (Equal 0s and 1s)Range Sum Query 2D - ImmutableProduct of Array Except Self
Detecting loops or cycles in linked lists, state machines, or sequence generators.
Finding the midpoint of a singly linked structure in one single pass without length counting.
Problems with cyclic number sequences (e.g., Happy Number).
MENTAL MODEL & BLUEPRINT
// Floyd's algorithm: meeting point proof 2(s) = f
let slow = head, fast = head
while (fast && fast.next) {
slow = slow.next
fast = fast.next.next
if (slow === fast) {
// Cycle detected. To find entry: reset slow to head, advance both by 1
slow = head
while (slow !== fast) {
slow = slow.next
fast = fast.next
}
return slow // entry node
}
}
return null // no cycle
Where it lives in production: Used in ring-buffer corruption checks, detecting infinite HTTP redirect loops in URL fetchers, and deadlock cycle detection in single-resource state graphs.
Interview Trap / Pitfall: Null pointer exceptions: checking `fast.next.next` before verifying both `fast` and `fast.next` are non-null.
CANONICAL BENCHMARKS
Linked List Cycle IIFind the Duplicate NumberMiddle of the Linked ListHappy Number
Requires constant time O(1) key lookups AND O(1) eviction based on access recency.
Tracking most/least recently used items with bounded capacity.
System design rounds asking for in-memory buffer pool structures.
MENTAL MODEL & BLUEPRINT
// LRU: Hash Map for O(1) lookup + Doubly Linked List for O(1) node reordering
class LRUCache {
// Sentinel head and tail eliminate boundary null checks
private head = new Node(0, 0)
private tail = new Node(0, 0)
private map = new Map<number, Node>()
moveToHead(node: Node) {
this.removeNode(node)
this.addNode(this.head, node)
}
evictTail(): Node {
const lru = this.tail.prev!
this.removeNode(lru)
return lru
}
}
Where it lives in production: The foundational data structure of Redis memory eviction policies, operating system page replacement algorithms, and database buffer pool management in SQLite/PostgreSQL.
Interview Trap / Pitfall: Dangling pointers when removing nodes; forgetting to remove the evicted node key from the lookup hash map; forgetting to update dummy head/tail sentinel bounds.
CANONICAL BENCHMARKS
LRU Cache (LeetCode 146)LFU Cache (LeetCode 460)Design In-Memory File System
Questions asking for "next greater element", "previous smaller element", or distance to next peak.
Calculating maximum areas under histograms or stock span periods.
Finding maximums across a sliding window in amortized O(1) per step.
MENTAL MODEL & BLUEPRINT
// Monotonic decreasing stack: each element pushed & popped at most once -> O(N)
const stack: number[] = [] // stores indices
const nextGreater = new Array(nums.length).fill(-1)
for (let i = 0; i < nums.length; i++) {
while (stack.length && nums[i] > nums[stack[stack.length - 1]]) {
const prevIdx = stack.pop()!
nextGreater[prevIdx] = nums[i]
}
stack.push(i)
}
Where it lives in production: Used in real-time APM telemetry agents (Datadog/Prometheus) to compute rolling max latency percentiles without sorting, and UI layout engines for text reflow bounds.
Interview Trap / Pitfall: Storing array values in the stack instead of array indices. Storing indices lets you calculate both the values and the positional distance.
CANONICAL BENCHMARKS
Daily TemperaturesLargest Rectangle in HistogramSliding Window MaximumNext Greater Element II
Finding the first or last occurrence of a condition in a sorted or rotated sequence.
Optimization questions phrased as: "Minimize the maximum workload" or "Find the minimum capacity to finish in D days".
Any monotonic predicate: if f(X) is true, f(X+1) is guaranteed true.
MENTAL MODEL & BLUEPRINT
// First True / Lower Bound invariant: search space always partitioned into [F, F, ..., T, T]
let low = 0, high = searchSpaceMax, ans = -1
while (low <= high) {
const mid = low + Math.floor((high - low) / 2)
if (isFeasible(mid)) {
ans = mid // record candidate
high = mid - 1 // try to find smaller feasible answer
} else {
low = mid + 1 // mid is too small
}
}
return ans
Where it lives in production: Powers B-Tree index leaf seeks in databases, `git bisect` for automated regression bug identification, and cluster autoscaler capacity thresholds.
Input consists of start and end timestamps or ranges `[start, end]`.
Questions asking to merge overlapping blocks, detect calendar conflicts, or find peak concurrent usage.
Scheduling the maximum number of non-overlapping jobs.
MENTAL MODEL & BLUEPRINT
// Sweepline: split intervals into discrete start (+1) and end (-1) time events
const events: [time: number, delta: number][] = []
for (const [start, end] of intervals) {
events.push([start, +1], [end, -1])
}
// Sort by time; break ties by processing end (-1) before start (+1) if boundary contact is allowed
events.sort((a, b) => a[0] - b[0] || a[1] - b[1])
let concurrent = 0, peak = 0
for (const [_, delta] of events) {
concurrent += delta
peak = Math.max(peak, concurrent)
}
Where it lives in production: Core to calendar reservation systems, database transaction lock conflict detection, and cloud hypervisor VM CPU/memory allocation bin-packing.
Interview Trap / Pitfall: Sorting by start time vs. end time: use start time when merging or sweeping; sort by end time when greedily selecting the maximum number of non-conflicting tasks.
Topological Sort (Kahn’s Algorithm & DAG In-Degrees)
HOW TO SPOT IT IN AN INTERVIEW
Tasks or entities have prerequisite dependencies.
Must produce a valid execution sequence or detect circular dependencies.
Directed graphs where cycles cause deadlocks or invalid states.
MENTAL MODEL & BLUEPRINT
// Kahn's algorithm: in-degree tracking + BFS queue
const inDegree = new Map<string, number>()
const graph = new Map<string, string[]>()
// Initialize graph and in-degrees...
const queue: string[] = []
for (const [node, deg] of inDegree) {
if (deg === 0) queue.push(node)
}
const order: string[] = []
while (queue.length) {
const curr = queue.shift()!
order.push(curr)
for (const next of graph.get(curr) || []) {
inDegree.set(next, inDegree.get(next)! - 1)
if (inDegree.get(next) === 0) queue.push(next)
}
}
const hasCycle = order.length !== totalNodes
Where it lives in production: The exact algorithm running inside CI/CD engines (GitHub Actions/GitLab CI), Terraform infrastructure dependency graphs, npm/pip package managers, and DB migration runners.
Interview Trap / Pitfall: Failing to detect cycles: if `sortedOrder.length !== totalNodes`, a cycle exists and no valid schedule is possible.
CANONICAL BENCHMARKS
Course Schedule I & IIAlien DictionarySequence Reconstruction
// BFS level-by-level with immediate visited marking
const queue = [start]
const visited = new Set([start])
let steps = 0
while (queue.length) {
const levelSize = queue.length
for (let i = 0; i < levelSize; i++) {
const node = queue.shift()!
if (node === target) return steps
for (const neighbor of getNeighbors(node)) {
if (!visited.has(neighbor)) {
visited.add(neighbor) // mark immediately!
queue.push(neighbor)
}
}
}
steps++
}
Where it lives in production: Used in peer-to-peer gossip network peer discovery, crawler URL depth limiting, social network "degrees of separation", and distributed tracer hop counts.
Interview Trap / Pitfall: Marking a node as visited when popping from the queue instead of when pushing to the queue (causes duplicate pushes and exponential memory explosion).
CANONICAL BENCHMARKS
Word LadderShortest Path in Binary MatrixRotting OrangesBinary Tree Level Order Traversal
Where it lives in production: Powers compiler AST validation, recursive RBAC permission inheritance trees, regex engine backtracking, and recursive file-system walkers.
Interview Trap / Pitfall: Forgetting to revert state changes (backtrack) before returning from recursive calls; missing base case termination causing call stack overflows.
CANONICAL BENCHMARKS
Number of IslandsWord SearchLowest Common Ancestor of a Binary TreeSubsets / Permutations
Finding the shortest path in a network with non-negative variable weights/costs/latencies.
Multi-hop routing where edge costs are latency, toll, or bandwidth constraints.
MENTAL MODEL & BLUEPRINT
// Dijkstra with Min-Priority Queue
const dist = new Map<Node, number>()
dist.set(source, 0)
const minHeap = new PriorityQueue((a, b) => a.cost - b.cost)
minHeap.push({ node: source, cost: 0 })
while (!minHeap.isEmpty()) {
const { node, cost } = minHeap.pop()!
if (cost > (dist.get(node) ?? Infinity)) continue // skip stale entry!
for (const edge of graph.get(node) || []) {
const nextCost = cost + edge.weight
if (nextCost < (dist.get(edge.to) ?? Infinity)) {
dist.set(edge.to, nextCost)
minHeap.push({ node: edge.to, cost: nextCost })
}
}
}
Where it lives in production: The backbone of IP routing protocols (OSPF, IS-IS), GPS road navigation algorithms, and latency-based traffic routing in Envoy/Istio service meshes.
Interview Trap / Pitfall: Does NOT work with negative weights (use Bellman-Ford); forgetting to skip stale entries popped from the priority queue if a shorter distance was already finalized.
CANONICAL BENCHMARKS
Network Delay Time (LeetCode 743)Path with Minimum EffortCheapest Flights Within K Stops
Where it lives in production: Used in cloud cluster network partition detection (split-brain detection), image connected-component segmentation, and identity resolution engines deduplicating user records.
Interview Trap / Pitfall: Omitting path compression in `find` or union by rank/size; both optimizations together give near constant-time inverse Ackermann O(α(N)) performance.
CANONICAL BENCHMARKS
Number of Connected Components in an Undirected GraphRedundant Connection (Cycle detection)Accounts Merge (LeetCode 721)Friend Circles
Tier 2 · Scale & SystemsTime: O(L) per search/insertSpace: O(Σ · L · N)Partitioning, Trees & Streaming
Trie (Prefix Tree & Radix Tree)
HOW TO SPOT IT IN AN INTERVIEW
Fast prefix searches, wildcard dictionary queries, or autocomplete suggestions.
Looking up the longest prefix match among a set of keys.
Word game lookups or spell-checker dictionaries.
MENTAL MODEL & BLUEPRINT
// Trie Node with hash map children for arbitrary Unicode/ASCII support
class TrieNode {
children = new Map<string, TrieNode>()
isEndOfWord = false
}
class Trie {
root = new TrieNode()
insert(word: string) {
let curr = this.root
for (const char of word) {
if (!curr.children.has(char)) curr.children.set(char, new TrieNode())
curr = curr.children.get(char)!
}
curr.isEndOfWord = true
}
startsWith(prefix: string): boolean {
let curr = this.root
for (const char of prefix) {
if (!curr.children.has(char)) return false
curr = curr.children.get(char)!
}
return true
}
}
Where it lives in production: The core engine of CIDR longest-prefix-match IP routing tables, search typeahead auto-complete, and URL path matching in HTTP routers (Nuxt, Express, Radix Router).
Interview Trap / Pitfall: Memory bloat when using fixed 26-pointer arrays for sparse character sets. In production systems, compress single-child nodes (Radix / Patricia Tree) or use a hash map for children.
CANONICAL BENCHMARKS
Implement Trie (Prefix Tree)Design Add and Search Words Data StructureWord Search II
Finding the top K frequent elements, Kth largest value, or closest K items.
Processing unbounded streaming inputs where you cannot fit all items in memory to sort.
Merging K pre-sorted data streams into one.
MENTAL MODEL & BLUEPRINT
// Find K largest elements using a Min-Heap of size K -> O(N log K)
const minHeap = new MinPriorityQueue()
for (const num of stream) {
minHeap.enqueue(num)
if (minHeap.size() > k) {
minHeap.dequeue() // discard the smallest; top K remain
}
}
return minHeap.toArray()
Where it lives in production: Continuous high-frequency analytics (top 100 API consumers in Datadog), priority job processing in message brokers (RabbitMQ/Celery), and external merge-sorting of large database logs.
Interview Trap / Pitfall: Using a Max-Heap when finding the K largest items: that requires O(N log N) space and time. Instead, keep a MIN-HEAP of size K; when size exceeds K, evict the minimum. The remaining K elements are the largest!
CANONICAL BENCHMARKS
Top K Frequent ElementsKth Largest Element in an ArrayMerge K Sorted ListsFind Median from Data Stream
Finding the minimum cost, maximum profit, or total number of ways to reach a state.
Future choices depend on past states, making greedy decisions fail.
Comparing two sequences (diff, alignment, edit distance).
MENTAL MODEL & BLUEPRINT
// 1D rolling array DP: Coin Change minimum coins
const dp = new Array(amount + 1).fill(Infinity)
dp[0] = 0 // base case
for (let i = 1; i <= amount; i++) {
for (const coin of coins) {
if (i - coin >= 0) {
dp[i] = Math.min(dp[i], dp[i - coin] + 1)
}
}
}
return dp[amount] === Infinity ? -1 : dp[amount]
Where it lives in production: The foundation of the Myers diff algorithm (powering `git diff`), cost-based database query execution planners, and cloud budget resource allocation.
Interview Trap / Pitfall: Allocating full 2D tables when the state recurrence only depends on the previous row; verify whether 1D rolling array optimization can reduce space from O(N*M) to O(M).
Tier 2 · Scale & SystemsTime: O(1) per bit operationSpace: O(1)Scale, State & Probabilistic
Bit Manipulation & Bitmasks
HOW TO SPOT IT IN AN INTERVIEW
Representing combinations of up to 30 boolean flags in a single integer.
Finding single numbers, missing elements, or bit parity.
Low-level network protocol header decoding and mask filtering.
MENTAL MODEL & BLUEPRINT
// Bitmask flag operations
const READ = 1 << 0, WRITE = 1 << 1, EXEC = 1 << 2
let permissions = 0
permissions |= READ | WRITE // Set flags
const canWrite = (permissions & WRITE) !== 0 // Check flag
permissions &= ~WRITE // Clear flag
permissions ^= EXEC // Toggle flag
Where it lives in production: Powers POSIX file permissions (`chmod 755`), RBAC permission bitfields, IPv4 subnet masking (`CIDR /24`), and compact binary wire protocols (TCP/IP flags).
Interview Trap / Pitfall: Operator precedence in JavaScript/Python: `==` has higher precedence than `&`. Always wrap bit operations in parentheses: `(flags & READ_MASK) !== 0`.
CANONICAL BENCHMARKS
Single Number (XOR cancellation)Subsets using BitmaskCounting BitsNumber of 1 Bits (Brian Kernighan’s algorithm)
Probabilistic Data Structures (Bloom Filter & HyperLogLog)
HOW TO SPOT IT IN AN INTERVIEW
Scale is massive (hundreds of millions of items) where exact sets exceed available RAM.
Allowed to have small, bounded false-positive rates, but zero false-negatives.
Cardinality estimation (distinct counting) over streaming data.
MENTAL MODEL & BLUEPRINT
// Conceptual Bloom filter: k independent hashes set bits in a fixed bit array
class BloomFilter {
private bits: Uint8Array
constructor(sizeInBytes: number, private hashCount: number) {
this.bits = new Uint8Array(sizeInBytes)
}
add(key: string) {
for (const bitIndex of this.getHashIndices(key)) {
this.bits[bitIndex >> 3] |= 1 << (bitIndex & 7)
}
}
mightContain(key: string): boolean {
for (const bitIndex of this.getHashIndices(key)) {
if ((this.bits[bitIndex >> 3] & (1 << (bitIndex & 7))) === 0) {
return false // Guaranteed NOT in set! (Zero false negatives)
}
}
return true // Probably in set (Small false positive chance)
}
}
Where it lives in production: Used in Cassandra/RocksDB SSTable reads to avoid unnecessary disk I/O, web crawlers to prevent re-crawling URLs, and Redis `PFADD`/`PFCOUNT` (HyperLogLog) for million-user DAU tracking.
Interview Trap / Pitfall: Assuming standard Bloom filters support item deletion (they do not because clearing a bit would break other keys that hashed to that same bit; use Counting Bloom Filters instead).
CANONICAL BENCHMARKS
Design a system to test if a username is taken before database queryEstimate unique daily visitors over a 50GB log stream with <1% error using <2KB RAMDesign a distributed rate limiter for millions of concurrent users