Algorithms and Data Structures Senior cheat sheet: interview answers

Every question of this level with its correct answer and explanation, on one page for a quick review before the interview.

  1. 1. Why does Dijkstra's algorithm give wrong results with negative edge weights?

    Correct answer: A finalized vertex could still get shorter via a negative edge

    Dijkstra assumes that once the closest vertex is taken from the queue, no later path can be shorter. A negative edge breaks that assumption. Bellman-Ford handles negative weights in O(V × E) and also detects negative cycles.

  2. 2. What extra capability does Bellman-Ford have compared with Dijkstra?

    Correct answer: It works with negative weights and detects negative cycles

    It relaxes all edges V - 1 times; if a V-th pass still improves a distance, there's a negative cycle. The price is O(V × E), much slower than Dijkstra's O((V + E) log V).

  3. 3. How does A* differ from Dijkstra's algorithm?

    Correct answer: It adds an estimate of the remaining distance

    A* orders vertices by g + h: the known cost plus an estimate to the goal, such as straight-line distance on a map. If h never overestimates (admissible), the path is still optimal, and far fewer vertices are explored.

  4. 4. What is the complexity of Floyd-Warshall, and when is it a reasonable choice?

    Correct answer: O(V³); for all-pairs shortest paths on small, dense graphs

    It's three nested loops over vertices, updating dist[i][j] through every intermediate k. Simple and handles negative edges (without negative cycles), but at V = 10,000 it's already 10¹² steps.

  5. 5. How do Prim's and Kruskal's algorithms differ?

    Correct answer: Prim grows one tree from a vertex; Kruskal joins forests by cheapest edges

    Both compute a minimum spanning tree. Prim adds the cheapest edge leaving the current tree (heap of edges); Kruskal sorts all edges and uses union-find to skip cycles. Kruskal is natural for sparse edge lists, Prim for dense graphs.

  6. 6. What makes union-find operations nearly O(1)?

    Correct answer: Path compression plus union by rank or size

    Path compression points nodes directly at the root during find; union by rank attaches the shorter tree under the taller. Together they give O(α(n)) amortized, where α (inverse Ackermann) is below 5 for any realistic n.

  7. 7. What problem does a Fenwick tree (binary indexed tree) solve?

    Correct answer: Prefix sums with updates, both in O(log n)

    Plain prefix sums make queries O(1) but updates O(n). A Fenwick tree balances both at O(log n) using the lowest set bit of the index (i & -i) to jump between ranges.

  8. 8. When would you choose a segment tree over a Fenwick tree?

    Correct answer: For range queries like min or max, or for range updates

    Fenwick trees fit invertible operations like sums. A segment tree stores an aggregate per segment and supports any associative operation (min, max, gcd) and, with lazy propagation, range updates. It uses about 2n to 4n nodes.

  9. 9. What can a Bloom filter tell you about a key?

    Correct answer: "Definitely not present" or "maybe present"

    It sets k bits per key with k hash functions. If any bit is 0, the key was never added; if all are 1, it might be a false positive. It never gives false negatives and uses a few bits per key, which is why databases use it to skip disk reads.

  10. 10. Why can't you delete an element from a standard Bloom filter?

    Correct answer: Its bits may be shared with other keys

    Clearing a bit could make another key look absent. A counting Bloom filter keeps small counters instead of bits to allow deletion, at the cost of more memory.

  11. 11. What does HyperLogLog estimate, and why is it popular?

    Correct answer: The number of distinct items, in a few kilobytes

    It hashes items and tracks the longest run of leading zeros per bucket; a run of k zeros suggests about 2ᵏ distinct values. With about 12 KB it gives roughly 1% error. Redis PFCOUNT and analytics systems use it for unique visitors.

  12. 12. What advantage does consistent hashing give a distributed cache?

    Correct answer: Adding or removing a node remaps only about 1/n of the keys

    With hash(key) % n changing n reshuffles almost every key. On a hash ring a key goes to the next node clockwise, so only keys near the changed node move. Virtual nodes smooth out the load.

  13. 13. What is a skip list?

    Correct answer: A sorted list with random express lanes for fast search

    Each node gets a random height; higher levels skip more nodes. Search, insert and delete are O(log n) on average, and the structure is simpler to make concurrent than a balanced tree. Redis sorted sets use skip lists.

  14. 14. Why do databases use B-trees rather than binary search trees for indexes?

    Correct answer: Wide nodes match disk pages, so lookups need few page reads

    A node holds hundreds of keys, so a tree over millions of rows is only 3-4 levels deep, and each level is one disk page read. A binary tree would be about 20 levels with poor locality.

  15. 15. What trade-off do LSM trees make compared with B-trees?

    Correct answer: Faster batched writes, but slower reads and compaction

    Writes go to memory and are flushed as sorted files, so disk writes are sequential. Reads may check several files (Bloom filters help), and background compaction merges them. Cassandra, RocksDB and LevelDB use LSM trees.

  16. 16. What is the average complexity of quickselect for finding the k-th smallest element?

    Correct answer: O(n)

    Like quicksort it partitions, but it recurses only into the side that contains position k, so the work is n + n/2 + n/4 + ... ≈ 2n. The worst case is O(n²); median of medians guarantees O(n) with a bigger constant.

  17. 17. How do you pick a uniformly random sample of k items from a stream of unknown length?

    Correct answer: Reservoir sampling: keep item i with probability k/i

    After any number of items each one is in the reservoir with equal probability k/n, using O(k) memory and one pass. Taking every k-th item isn't uniform and depends on the stream length.

  18. 18. What is wrong with shuffling an array via arr.sort(() => Math.random() - 0.5)?

    Correct answer: The result is biased; Fisher-Yates is uniform

    Sort algorithms assume a consistent comparator; random answers make some permutations much more likely, depending on the engine. Fisher-Yates swaps each position with a random earlier one in O(n) and is uniform.

  19. 19. How do you sort a 200 GB file on a machine with 8 GB of RAM?

    Correct answer: Sort chunks that fit in memory, then k-way merge them with a heap

    External merge sort writes sorted runs to disk and then merges them, reading each run sequentially. The heap picks the smallest head among k runs in O(log k). Splitting by first character doesn't balance the pieces.

  20. 20. How do you merge k sorted lists with n elements in total efficiently?

    Correct answer: A min-heap of the k current heads: O(n log k)

    Each step pops the smallest head and pushes the next element from the same list. Merging one by one is O(n × k) in the worst case; concatenating and sorting is O(n log n).

  21. 21. What is the key idea of the Rabin-Karp string search?

    Correct answer: A rolling hash compares the pattern with each window in O(1)

    When the window slides by one character, the hash is updated by removing the old character and adding the new one. Only windows with a matching hash are compared character by character. It shines when searching for many patterns at once.

  22. 22. How does KMP achieve O(n + m) string search?

    Correct answer: A prefix function says how far to shift without rereading text

    For each position of the pattern, the prefix function stores the length of the longest proper prefix that's also a suffix. On a mismatch the pattern jumps by that amount, so the text pointer never moves back.

  23. 23. By the master theorem, what is the complexity of T(n) = 2T(n/2) + O(n)?

    Correct answer: O(n log n)

    Two halves with linear work to combine is the merge sort recurrence. Each of the log n levels of recursion does O(n) work in total. T(n) = 2T(n/2) + O(1) would be O(n), and T(n) = T(n/2) + O(1) is binary search, O(log n).

  24. 24. What does it mean that the 0/1 knapsack DP is pseudo-polynomial?

    Correct answer: O(n × W) depends on the value W, which is exponential in its bit length

    The table has W columns, and each extra bit in W doubles it, so the work is exponential in the input size. Knapsack is NP-hard; the DP is fast only when capacities are small integers.

  25. 25. An interviewer describes a problem that reduces to the traveling salesman problem. What's a sensible response?

    Correct answer: Note it's NP-hard, then propose heuristics or exact DP for small n

    No polynomial algorithm is known. Exact bitmask DP is O(n² × 2ⁿ), fine up to about 20 cities. For real routes you use heuristics such as nearest neighbor plus 2-opt, or a solver, and accept a near-optimal answer.

  26. 26. What does bitmask DP use as its state?

    Correct answer: An integer whose bits mark the elements used

    With n up to about 20, subsets fit in an integer: mask | (1 << i) adds element i, mask & (1 << i) checks it. States like dp[mask][last] solve TSP and assignment problems in O(2ⁿ × n²).

  27. 27. How do you reduce the memory of an LCS or edit distance DP from O(n × m) to O(m)?

    Correct answer: Keep only the previous row, since each cell depends on it

    Cell (i, j) needs only (i-1, j), (i, j-1) and (i-1, j-1). Two rows (or one with a saved diagonal) are enough for the length. Reconstructing the actual alignment then needs extra work, for example Hirschberg's algorithm.

  28. 28. What is amortized analysis with the "accounting" or "potential" method?

    Correct answer: Charging cheap operations extra to pay for rare expensive ones

    It gives a worst-case bound for a sequence of operations, with no probability involved. Each push to a dynamic array "saves" a constant that later pays for copying during a resize. Averaging over random inputs is average-case analysis, a different thing.

  29. 29. What is hash flooding?

    Correct answer: Sending colliding keys so a hash table becomes O(n)

    If an attacker can predict the hash function, crafted request parameters land in one bucket and every insert becomes linear, enough to stall a server. Languages defend with randomly seeded hashes (SipHash) or tree-based buckets.

  30. 30. Why can an O(n log n) algorithm lose to an O(n²) one on real inputs?

    Correct answer: Big O hides constants, and for small n they dominate

    Insertion sort beats merge sort below a few dozen elements thanks to tiny overhead and cache-friendly access. That's why Timsort and introsort switch to insertion sort for small runs.

  31. 31. Why does Timsort perform so well on real-world data?

    Correct answer: It detects existing sorted runs and merges them

    Real data is often partially ordered: appended logs, mostly sorted lists. Timsort finds ascending (or reversed descending) runs, extends short ones with insertion sort and merges them with galloping, approaching O(n) on nearly sorted input.

  32. 32. What is introsort and why is it used in C++ std::sort?

    Correct answer: Quicksort that falls back to heapsort when recursion gets too deep

    Quicksort is fast on average, but its O(n²) worst case can be triggered. Introsort limits recursion depth to about 2 log n and switches to heapsort, guaranteeing O(n log n) while keeping quicksort speed.

  33. 33. Which structure lets you find all intervals overlapping a point in O(log n + k)?

    Correct answer: An interval tree

    An interval tree is a balanced BST ordered by start, where each node also stores the maximum end in its subtree, so whole branches can be skipped. Calendars and genome tools use it.

  34. 34. What does Tarjan's or Kosaraju's algorithm compute?

    Correct answer: Strongly connected components of a directed graph

    A strongly connected component is a group where every vertex reaches every other. Both algorithms run in O(V + E) with DFS. Collapsing SCCs turns any directed graph into a DAG, useful for dependency analysis.

  35. 35. Why does React's reconciliation run in O(n) when a general tree diff is about O(n³)?

    Correct answer: It uses element types and keys as heuristics

    The minimal tree edit distance is expensive. React compares level by level: a changed type replaces the subtree, and key matches children between renders. These heuristics are almost always right for UI code.

  36. 36. Which algorithm do git diff and many diff tools use by default?

    Correct answer: Myers' algorithm, based on the shortest edit script

    Myers finds the shortest sequence of insertions and deletions in O((n + m) × d), where d is the number of differences, so similar files diff quickly. It's closely related to the longest common subsequence.

  37. 37. A virtualized list renders only visible rows of 100,000 items with different heights. How does it find the first visible row quickly?

    Correct answer: Binary search over cumulative row offsets

    Prefix sums of row heights are sorted, so binary search finds the row at scrollTop in O(log n). Walking is O(n) per scroll; dividing by an average drifts when heights vary.

  38. 38. What does structural sharing in persistent data structures give you?

    Correct answer: New versions reuse unchanged parts, so updates don't copy everything

    Updating one leaf of a tree copies only the path to the root, O(log n), and old versions stay valid. Immutable updates in Redux, Immer and Clojure collections rely on this; it also makes === change checks cheap.

  39. 39. When does LFU beat LRU as a cache eviction policy?

    Correct answer: When a few items stay popular while scans touch many items once

    One big scan can push all hot items out of an LRU cache. LFU keeps frequently used items, but adapts slowly when popularity shifts. Modern caches (W-TinyLFU in Caffeine) combine recency and frequency.

  40. 40. How does a token bucket rate limiter work?

    Correct answer: Tokens refill at a fixed rate; each request spends one or is rejected

    The bucket's capacity allows short bursts, and the refill rate bounds the average. It needs only two numbers per key: tokens and last refill time, so it's O(1) per request.

  41. 41. What is the complexity of building a binary heap from n unsorted elements with sift-down (heapify)?

    Correct answer: O(n)

    Most nodes are near the bottom and sift down only a little: half the nodes move 0 levels, a quarter 1 level and so on. The sum converges to O(n). Inserting elements one by one would be O(n log n).

  42. 42. Why can't you run binary search efficiently on a linked list?

    Correct answer: Reaching the middle takes O(n), so there's no random access

    Binary search relies on O(1) access by index. On a list each halving step walks half the remaining nodes, so the total is O(n). Skip lists add extra pointers to restore O(log n).

  43. 43. Which approach answers "is this word in the dictionary?" for millions of words with the least memory, if rare false positives are fine?

    Correct answer: A Bloom filter

    A Bloom filter needs about 10 bits per word for a 1% false positive rate, regardless of word length. A trie or a sorted array stores the words themselves, which takes far more memory.

  44. 44. What is the time complexity of building a suffix array naively by sorting all suffixes?

    Correct answer: O(n² log n), because comparing suffixes costs O(n)

    There are n suffixes and n log n comparisons, each of which may read O(n) characters. Prefix doubling brings it to O(n log n), and SA-IS to O(n). Suffix arrays answer substring queries with binary search.

  45. 45. Why are tries often replaced by hash maps or radix trees in production?

    Correct answer: Plain tries waste memory on nodes with a single child

    A node per character with child maps is heavy. Radix (Patricia) trees compress chains of single children into one edge. Routers in web frameworks (find-my-way in Fastify) use radix trees for URL matching.

  46. 46. Which algorithm should you use to detect a cycle in module imports at build time?

    Correct answer: DFS with three states, or Kahn's algorithm

    Imports form a directed graph; a cycle is a back edge in DFS, or leftover vertices after Kahn's topological sort. Union-find detects cycles only in undirected graphs, so it would report false cycles for diamonds.

  47. 47. Why can't union-find detect cycles in a directed graph?

    Correct answer: It ignores direction, so a diamond looks like a cycle

    Union-find tracks connectivity, not direction. In a DAG two paths to the same vertex (a diamond) would join already connected vertices, which looks like a cycle but isn't one.

  48. 48. What is the complexity of checking whether a number is a power of two with n > 0 && (n & (n - 1)) === 0?

    Correct answer: O(1)

    It's a single bitwise operation on a fixed-width integer. In JavaScript bitwise operators work on 32-bit integers, so for values above 2³¹ you need another approach, such as Number.isInteger(Math.log2(n)) or BigInt.

  49. 49. Why does 0.1 + 0.2 !== 0.3 matter for algorithms?

    Correct answer: Float sums aren't exact, so compare with a tolerance

    Binary floating point can't represent 0.1 exactly, and errors accumulate in long sums or geometry code. Compare with Math.abs(a - b) < epsilon, use integers (cents instead of dollars), or BigInt for exact integer math.

  50. 50. Which statement about average and worst case of hash table operations is correct?

    Correct answer: Average O(1) assumes a good hash; the worst case is still O(n)

    Expected O(1) relies on keys spreading evenly. Some implementations (Java 8 HashMap) turn long chains into trees, bounding the worst case at O(log n), but in general a hash table promises only average-case speed.

  51. 51. What is cache-friendly about iterating a 2D array row by row in C-like layouts?

    Correct answer: Rows are contiguous, so reads hit the same cache lines

    With row-major layout a[i][j] and a[i][j+1] are neighbors. Iterating by columns jumps a whole row each step and misses the cache, which can be several times slower for the same O(n²) work.

  52. 52. Which algorithm finds the maximum flow in a network?

    Correct answer: Edmonds-Karp (Ford-Fulkerson with BFS)

    It repeatedly finds a shortest augmenting path with BFS and pushes flow along it, in O(V × E²). Max flow also solves bipartite matching, for example assigning tasks to workers.

  53. 53. A recursive solution is correct but times out because of repeated subproblems with three parameters. What's the usual first fix?

    Correct answer: Memoize each parameter tuple, e.g. in a Map

    The number of distinct states bounds the work once each state is cached. In JavaScript a key such as ${i},${j},${k} or a 3D array works. Then consider bottom-up order to avoid deep recursion.

  54. 54. What is the expected number of comparisons for a successful lookup in a hash table with chaining and load factor α?

    Correct answer: About 1 + α/2

    With uniform hashing a chain has α elements on average, and a successful search scans about half of it. That's why tables keep α below a constant such as 0.75: lookups stay a few comparisons long.

  55. 55. What does a monotonic deque give you in the "sliding window maximum" problem?

    Correct answer: The maximum of each window in O(1), O(n) overall

    The deque keeps indices of decreasing values: new values pop smaller ones from the back, and indices that left the window are dropped from the front. Every index enters and leaves once. A median needs two heaps instead.

  56. 56. How do you maintain the running median of a stream efficiently?

    Correct answer: A max-heap for the lower half, a min-heap for the upper

    Keep the heaps balanced in size; the median is one of the roots or their average. Each insert is O(log n). A sorted array needs O(n) shifting per insert, and the average is not the median.

  57. 57. What does it mean that a problem is NP-complete?

    Correct answer: It's in NP, and every NP problem reduces to it in polynomial time

    Solutions can be checked quickly, but no polynomial algorithm to find them is known. A polynomial algorithm for any NP-complete problem would solve all of NP. Examples: SAT, graph coloring, subset sum.

  58. 58. Why is the recursion depth of quicksort a concern, and how is it bounded?

    Correct answer: Bad pivots give depth n; recurse into the smaller side

    Recursing into the smaller partition and looping over the larger one guarantees O(log n) stack depth even when the time degrades. Introsort also caps depth and switches to heapsort.

  59. 59. Which structure would you use for an autocomplete that ranks suggestions by popularity?

    Correct answer: A trie with the top suggestions cached at each node

    The trie finds the prefix node in O(length of the prefix); caching the top k per node avoids walking the whole subtree on each keystroke. A plain map can't list words by prefix efficiently.

  60. 60. What problem does a ring buffer with head and tail indices solve for a high-throughput queue?

    Correct answer: O(1) enqueue and dequeue without shifting

    Indices wrap around with % capacity, so the buffer is reused forever. It's how audio buffers, network drivers and log collectors queue data. When full, it either blocks, drops new items or overwrites the oldest.

  61. 61. What is the lower bound for finding an element in an unsorted array, and why?

    Correct answer: Ω(n): any unchecked position could hold the target

    An adversary argument: if an algorithm skips a position, the target could be there. Hashing helps only after an O(n) preprocessing step that builds the table.

  62. 62. Why is DFS preferred over BFS for some puzzles despite BFS finding shortest solutions?

    Correct answer: DFS stores one path; BFS stores a whole frontier

    With branching factor b and depth d, BFS keeps up to bᵈ states in its queue. Iterative deepening DFS gets the best of both: shortest solutions with O(d) memory, at the cost of repeating the shallow levels.

  63. 63. What is the complexity of Array.prototype.sort in V8 on an array that's already sorted?

    Correct answer: About O(n)

    Timsort detects that the whole array is one ascending run and only does a linear check. This is one reason to prefer the built-in sort over a handwritten quicksort.

  64. 64. How do you find all pairs that sum to a target in an array with duplicates, without double counting?

    Correct answer: Count values in a map and pair counts, handling x = target - x

    For each distinct x pair it with count[target - x]; when x equals its complement use c × (c - 1) / 2. Process each value pair once (x < complement). A Set loses the counts.

  65. 65. Which statement about recursion and the call stack in JavaScript is correct?

    Correct answer: Tail calls are in the spec, but only Safari has them

    ES2015 specified proper tail calls in strict mode, but V8 and SpiderMonkey don't ship them. So in Chrome and Node.js a tail-recursive function still uses a frame per call and can overflow.

  66. 66. What is the main advantage of Dijkstra with a Fibonacci heap over a binary heap?

    Correct answer: Amortized O(1) decrease-key: O(E + V log V)

    On dense graphs this beats O((V + E) log V). In practice binary heaps (often with lazy deletion instead of decrease-key) are usually faster because Fibonacci heaps have large constants.

  67. 67. How do you check whether two words are one edit apart in O(n)?

    Correct answer: Two pointers, allowing a single skip or mismatch

    If lengths differ by more than one, the answer is no. Otherwise move pointers together and, at the first mismatch, skip a character in the longer word (or both for equal length). The full DP is O(n × m).

  68. 68. What does randomization give quicksort?

    Correct answer: Expected O(n log n) for every input

    With a random pivot no fixed input is consistently bad, so the expectation holds for any input, including adversarial ones. The worst case is still possible, just extremely unlikely.

  69. 69. Which approach counts inversions (pairs i < j with a[i] > a[j]) in O(n log n)?

    Correct answer: Merge sort, counting left elements each right one passes

    When an element from the right half is merged before the remaining left elements, it forms an inversion with each of them. A Fenwick tree over values also works in O(n log n).

  70. 70. Why does a good hash function for strings process every character?

    Correct answer: Hashing only a prefix makes keys with a shared prefix collide

    Early Java versions hashed only some characters of long strings, and URLs with the same start collided heavily. The cost of reading the whole key is the price of an even spread.

  71. 71. What does the "sparse table" structure answer in O(1)?

    Correct answer: Range minimum queries on a static array

    It precomputes minimums of all ranges of length 2ᵏ in O(n log n). Any range is covered by two overlapping power-of-two ranges, and min doesn't care about overlap. Updates would require rebuilding.

  72. 72. What is the main reason to prefer an adjacency matrix over adjacency lists?

    Correct answer: O(1) edge checks on dense graphs

    Checking matrix[u][v] is instant, and for dense graphs the O(V²) memory isn't wasted. For sparse graphs lists win on memory and neighbor iteration.

  73. 73. An algorithm runs in O(n) but allocates a new array on every iteration of a hot loop. What's the likely real-world issue?

    Correct answer: Garbage collection pressure that Big O doesn't show

    Allocation and GC pauses add constant factors and latency spikes. Reusing buffers or typed arrays often gives large speedups without changing the asymptotic complexity.

  74. 74. What does the "two heaps" trick fail to support efficiently, compared with a balanced BST?

    Correct answer: Removing an arbitrary element from the middle

    Heaps can only remove their root cheaply. For a sliding window median you need lazy deletion (marking removed values and skipping them later) or an ordered multiset, such as a balanced tree, that removes any value in O(log n).

  75. 75. Why is Array.prototype.indexOf inside filter a common hidden O(n²) in code reviews?

    const unique = items.filter((x, i) => items.indexOf(x) === i);

    Correct answer: indexOf scans the array for each element of filter

    Each of the n callbacks does a linear search, so 10,000 items mean up to 100 million comparisons. [...new Set(items)] does the same job in O(n). Spotting such nested scans is a typical senior review skill.