Algorithms and Data Structures Middle 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. How does merge sort work?
Correct answer: Split the array in halves, sort each half, then merge them
Merge sort divides until single elements remain, then merges sorted halves with two pointers. It's O(n log n) in every case and stable, but it needs O(n) extra memory for merging.
2. What is the main drawback of merge sort on arrays?
Correct answer: It needs O(n) extra memory for merging
The merge step writes into a temporary buffer. The time is O(n log n) regardless of the input, and the classic implementation is stable. On linked lists merge sort can be done without the extra buffer.
3. What is the worst case of quicksort and when does it happen?
Correct answer: O(n²), when pivots keep splitting the array very unevenly
If the pivot is always the smallest or largest element (for example, the first element of a sorted array), each partition removes only one element. Random pivots or median-of-three make this unlikely; the average is O(n log n).
4. Why is quicksort often faster than merge sort in practice despite the same O(n log n) average?
Correct answer: It sorts in place and accesses memory sequentially
Partitioning works inside the array with good cache locality and small constants. Its worst case is actually worse (O(n²)), and the usual in-place version is not stable.
5. What does partitioning do in quicksort?
Correct answer: Moves smaller values before the pivot and larger after it
After partitioning the pivot is in its final position, and the two sides are sorted recursively. The sides don't have to be equal in size, which is why the pivot choice matters.
6. Which sorting algorithm does V8 use for
Array.prototype.sort?Correct answer: Timsort
Since 2018 (V8 7.0)
sortuses Timsort: a hybrid of merge sort and insertion sort that finds already sorted runs. It's stable and O(n log n) in the worst case, and close to O(n) on nearly sorted data.7. Why can't any comparison sort beat O(n log n) in the worst case?
Correct answer: It must tell apart n! orderings: log(n!) ≈ n log n
Each comparison has two outcomes, so k comparisons distinguish at most 2ᵏ orderings. To identify one of n! orderings you need log₂(n!) comparisons, which is Θ(n log n).
8. When can counting sort beat O(n log n)?
Correct answer: For small integer keys in range k: O(n + k)
Counting sort doesn't compare elements: it counts how many times each key occurs and writes them back in order. It's great for ages or grades, but a huge range of keys makes the count array too large.
9. What is a binary heap (min-heap)?
Correct answer: A complete binary tree where each parent is no greater than its children
The smallest element is always at the root, but the rest are only partially ordered. A heap is usually stored in an array: the children of index
iare at2i + 1and2i + 2. The left-smaller rule describes a BST.10. What are the costs of the main operations of a binary heap?
Correct answer: Peek O(1), insert O(log n), extract min O(log n)
The minimum sits at the root. Insert adds to the end and "sifts up"; extraction moves the last element to the root and "sifts down". Both walk one path of height log n.
11. How do you find the k largest elements of a large array efficiently?
Correct answer: Keep a min-heap of size k and replace its root when you see a larger value
The heap always holds the k largest seen so far, and its root is the smallest of them. The total cost is O(n log k), which beats sorting (O(n log n)) when k is small, and works on streams too.
12. Does JavaScript have a built-in priority queue?
Correct answer: No, you write a heap yourself or use a library
There's no built-in heap in JavaScript.
Mapkeeps insertion order, not priority. In interviews you either implement a small binary heap or explain that you'd use one from a library.13. What does this binary search return when
targetis not in the array?function lowerBound(arr, target) { let lo = 0, hi = arr.length; while (lo < hi) { const mid = (lo + hi) >> 1; if (arr[mid] < target) lo = mid + 1; else hi = mid; } return lo; }Correct answer: The index where
targetcould be inserted keeping the orderThis is lower bound: the first index whose value is
>= target. If all values are smaller it returnsarr.length. It's the basis of many variations: counting occurrences, finding ranges, inserting into a sorted array.14. Why is
mid = lo + Math.floor((hi - lo) / 2)recommended in many languages instead of(lo + hi) / 2?Correct answer:
lo + hican overflow a fixed-size integerIn Java or C++ with 32-bit ints,
lo + hican exceed the maximum and become negative. JavaScript numbers are doubles, so this isn't a practical issue for array indices, but the habit is worth knowing.15. What does "binary search on the answer" mean?
Correct answer: Searching for the smallest value meeting a monotonic test
If "can we do it with x?" is false up to some point and true after it, you can binary search x. Example: the minimum ship capacity to deliver packages in D days, where each check is a greedy O(n) pass.
16. How do you find a value in a sorted array that was rotated, like
[4, 5, 6, 1, 2, 3], in O(log n)?Correct answer: Binary search, checking which half is sorted at each step
Compare
arr[lo]witharr[mid]to see which half is in order, then check whether the target falls into that half's range. Sorting first costs O(n log n), linear search O(n).17. What is the sliding window technique?
Correct answer: Moving the edges of a range while updating a summary
Instead of recomputing every subarray from scratch, the window adds the new element on the right and removes the old one on the left. Problems like "longest substring without repeating characters" become O(n).
18. Longest substring without repeating characters: what's the O(n) idea?
Correct answer: On a repeat, move the window's left edge past the old position
Store the last index of each character in a map. When the current character was seen inside the window, jump the left edge to
last + 1. Each index moves forward only, so the total work is O(n).19. Two Sum on a sorted array: what's the O(n) approach without extra memory?
Correct answer: Two pointers from both ends, moved by comparing the sum
Sortedness tells you which pointer to move: increasing the left value raises the sum, decreasing the right value lowers it. A hash map also works in O(n) but needs O(n) memory.
20. How do you merge overlapping intervals like
[[1,3],[2,6],[8,10]]?Correct answer: Sort by start, then extend the last merged interval or start a new one
After sorting by start, an interval overlaps the previous one exactly when its start is not after the previous end. One pass gives
[[1,6],[8,10]]. The total cost is O(n log n) for the sort.21. What is a monotonic stack used for?
Correct answer: Next greater element for every item in O(n)
The stack keeps indices whose values are decreasing. When a bigger value arrives, it pops the smaller ones: the new value is their "next greater" element. Each index is pushed and popped once, so the pass is O(n).
22. How do you implement a queue with two stacks so that each operation is amortized O(1)?
Correct answer: Push to "in"; pop from "out", refilling it from "in" when empty
Moving elements reverses their order, so the oldest ends up on top of "out". Each element is moved at most once, so n operations cost O(n) in total.
23. Which structure gives O(1) insertion and removal at both ends?
Correct answer: A deque (double-ended queue)
A deque is usually a ring buffer or a doubly linked list. It's the key structure for "sliding window maximum" in O(n): it keeps candidate indices in decreasing order of value.
24. How do you detect a cycle in a linked list with O(1) extra memory?
Correct answer: A slow and a fast pointer: they meet only if there's a cycle
This is Floyd's "tortoise and hare" algorithm. If there's a cycle, the fast pointer eventually laps the slow one; if not, it reaches
null. ASetalso works but takes O(n) memory.25. How do you find the middle of a linked list in one pass?
Correct answer: Slow and fast pointers: when fast ends, slow is in the middle
A singly linked list doesn't know its length, so you'd need two passes otherwise. The slow/fast pointer trick finds the middle in one pass with O(1) memory.
26. How do you reverse a singly linked list iteratively?
let prev = null, cur = head; while (cur) { const next = cur.next; // ? } return prev;Correct answer:
cur.next = prev; prev = cur; cur = next;Each node's pointer is flipped to the previous node, then both pointers move forward.
nextis saved first, otherwise the rest of the list would be lost. O(n) time, O(1) memory.27. How is an LRU cache with O(1)
getandputusually built?Correct answer: A hash map plus a doubly linked list ordered by recent use
The map finds a node by key; the list moves it to the front in O(1) and drops the tail when full. In JavaScript a
Mapalone works: it keeps insertion order, so delete and re-set a key on access and evictmap.keys().next().value.28. Why does BFS find the shortest path in an unweighted graph?
Correct answer: It visits vertices in order of their distance from the start
The queue processes all vertices at distance 1, then distance 2, and so on. The first time BFS reaches a vertex, it does so by a shortest path. With weighted edges you need Dijkstra instead.
29. Why do graph traversals keep a
visitedset?Correct answer: To avoid processing vertices twice or looping on cycles
Unlike trees, graphs can have cycles and several paths to the same vertex. Without
visiteda traversal can revisit vertices endlessly; with it every vertex is processed once, O(V + E).30. How do you count islands (connected groups of 1s) in a grid of 0s and 1s?
Correct answer: Start BFS or DFS at each unvisited 1 to mark its island
Each traversal marks one connected component, so the number of traversals started is the answer. Every cell is visited a constant number of times: O(rows × cols).
31. What is a topological sort?
Correct answer: An order of DAG vertices where every edge points forward
It's how build tools, package managers and task schedulers order work: a task comes after everything it depends on. It exists only if the graph has no cycles.
32. How does Kahn's algorithm compute a topological order?
Correct answer: Repeatedly remove a vertex that has no incoming edges
Keep in-degrees and a queue of vertices with in-degree 0. If the queue empties before all vertices are output, the graph has a cycle. The DFS version outputs vertices in reverse order of finishing, not of discovery.
33. How do you detect a cycle in a directed graph with DFS?
Correct answer: Track the current DFS path; an edge back into it is a cycle
Use three states: unvisited, in progress (on the stack) and done. Only an edge to an "in progress" vertex is a back edge. An edge to a "done" vertex is fine: it's just another path to the same place.
34. What does a union-find (disjoint set) structure support?
Correct answer: Merging sets and checking if two items share a set
union(a, b)merges two groups andfind(a)returns a group's representative. With path compression and union by rank both are nearly O(1). Typical uses: connected components, Kruskal's MST, "are these accounts the same person?"35. What is a trie good for?
Correct answer: Prefix lookups, such as autocomplete
Each node represents a prefix and its children are the next characters. Checking a prefix costs O(length of the prefix), regardless of how many words are stored.
36. Which tree traversal visits the values of a BST in sorted order?
Correct answer: In-order (left, node, right)
In-order visits everything smaller than a node before it and everything larger after it. Pre-order is handy for copying a tree, post-order for deleting it or evaluating expressions.
37. How do you traverse a binary tree level by level?
Correct answer: BFS with a queue, one queue length per level
Record
queue.lengthat the start of each level and process exactly that many nodes, pushing their children. This gives the levels separately, which many problems need (right side view, average per level).38. How do you compute the maximum depth of a binary tree recursively?
function depth(node) { if (!node) return 0; // ? }Correct answer:
return 1 + Math.max(depth(node.left), depth(node.right));The depth of a node is one more than the deeper of its subtrees, and an empty subtree has depth 0. Adding both subtrees would count nodes, not depth. The cost is O(n), with recursion depth equal to the height.
39. What problem do self-balancing trees (AVL, red-black) solve?
Correct answer: They keep the height O(log n), so operations stay fast
After inserts and deletes they rotate nodes to keep the tree roughly balanced. Ordered maps in many languages (Java
TreeMap, C++std::map) are red-black trees.40. Which two properties make a problem a good fit for dynamic programming?
Correct answer: Overlapping subproblems and optimal substructure
Overlapping subproblems means the same sub-results are needed many times, so caching them pays off. Optimal substructure means the best answer is built from best answers to subproblems.
41. What is the difference between memoization and tabulation?
Correct answer: Memoization caches recursive calls top-down; tabulation fills a table bottom-up
Both compute each subproblem once. Top-down is often easier to write and computes only what's needed; bottom-up avoids deep recursion and makes memory optimizations easier, for example keeping only the last row.
42. Climbing stairs: you can step 1 or 2 stairs at a time. How many ways are there to climb n stairs?
Correct answer:
ways(n) = ways(n - 1) + ways(n - 2), the Fibonacci recurrenceThe last move is either a single step from stair n - 1 or a double step from n - 2, so the counts add up. With two variables it's O(n) time and O(1) memory.
43. Why can a greedy algorithm fail for making change with coins
[1, 3, 4]and amount 6?Correct answer: Greedy takes 4 + 1 + 1 (three coins), while 3 + 3 uses only two
Taking the largest coin first is optimal for standard currencies but not for arbitrary coin sets. Dynamic programming over amounts (
dp[a] = 1 + min dp[a - coin]) always finds the minimum.44. What is the complexity of the coin change DP for amount A and k coin types?
Correct answer: O(A × k)
For each amount from 1 to A you try each of the k coins once. Exponential O(kᴬ) is the brute-force recursion without caching.
45. What is the longest common subsequence (LCS) of two strings?
Correct answer: The longest common sequence in order, gaps allowed
For "ABCBDAB" and "BDCABA" one LCS is "BCBA". The standard DP table is O(n × m). LCS is the idea behind
difftools.46. What does the Levenshtein (edit) distance measure?
Correct answer: Minimum inserts, deletes and substitutions to turn one into the other
It's computed with an O(n × m) DP table and powers spell checkers and "did you mean...?" suggestions. Counting differing positions in equal-length strings is the Hamming distance.
47. What is the idea of Kadane's algorithm for the maximum subarray sum?
Correct answer: Track the best sum ending here: extend it or start over
cur = Math.max(x, cur + x),best = Math.max(best, cur). A negative running sum only hurts, so it's dropped. One pass, O(n), instead of O(n²) for all subarrays.48. How many subsets does a set of n elements have, and why does that matter?
Correct answer: 2ⁿ, so generating all subsets is exponential
Each element is either in or out, giving 2ⁿ combinations. Backtracking that enumerates subsets is fine for n around 20 but not 50. n! is the number of permutations.
49. What is backtracking?
Correct answer: Building a solution step by step and undoing dead-end choices
It's a DFS over choices: add a choice, recurse, remove it. Pruning (stopping early when the partial solution can't work) is what keeps it practical. Classic problems: permutations, N-Queens, Sudoku.
50. How many permutations does an array of n distinct elements have?
Correct answer: n!
There are n choices for the first position, n - 1 for the second and so on. 10! is already 3.6 million, so generating all permutations works only for small n.
51. How can you avoid a stack overflow in deep recursion in JavaScript?
Correct answer: Rewrite it with a loop and an explicit stack
JavaScript engines (except Safari) don't implement tail call optimization, so the call stack is limited to roughly ten thousand frames. An explicit array used as a stack lives on the heap and can grow much larger.
52. What is the space complexity of a recursive DFS on a tree of height h?
Correct answer: O(h) for the call stack
At any time the stack holds one frame per level of the current path. For a balanced tree h is log n; for a degenerate one it's n.
53. What happens to a hash table when its load factor gets too high?
Correct answer: It grows the array and re-inserts (rehashes) all entries
The load factor is entries divided by buckets. When it passes a threshold, collisions become frequent, so the table grows, usually doubling. Rehashing is O(n) but rare, so inserts stay amortized O(1).
54. What makes a good hash function for a hash table?
Correct answer: It's fast and spreads keys evenly across buckets
Even distribution keeps chains short. Uniqueness is impossible when there are more keys than buckets, and keeping similar keys together would cause clusters of collisions.
55. What does the group anagrams problem usually use as a map key?
groupAnagrams(["eat", "tea", "tan", "ate", "nat"]); // [["eat", "tea", "ate"], ["tan", "nat"]]Correct answer: The word's sorted letters or letter counts
Anagrams share the same multiset of letters, so
"aet"(sorted) is the same for eat, tea and ate. Length or first letter would put non-anagrams together.56. How do you answer "sum of elements from i to j" many times on a static array?
Correct answer: Prefix sums once, then
prefix[j + 1] - prefix[i]per queryPreprocessing is O(n) and every query is O(1). If the array also changes between queries, prefix sums break and you need a Fenwick or segment tree.
57. Subarray sum equals k: why do we store counts of prefix sums in a hash map?
Correct answer: A subarray ending here sums to k if
prefix - kwas seenThe sum of
(i, j]equalsprefix[j] - prefix[i]. For each position, add how many earlier prefixes equalprefix - k. One pass, O(n), and it works with negative numbers, unlike a sliding window.58. What does Dijkstra's algorithm compute?
Correct answer: Shortest paths from one vertex when weights are non-negative
It repeatedly takes the unvisited vertex with the smallest known distance (from a priority queue) and relaxes its edges. With a binary heap it runs in O((V + E) log V). Negative weights break it.
59. Which data structure makes Dijkstra's algorithm efficient?
Correct answer: A priority queue (min-heap)
The heap gives the closest unvisited vertex in O(log V). With a plain queue the algorithm becomes BFS, which ignores weights; scanning all vertices for the minimum makes it O(V²).
60. What is the complexity of BFS or DFS on a graph stored as adjacency lists?
Correct answer: O(V + E)
Every vertex is processed once and every edge is looked at once (twice for undirected graphs). With an adjacency matrix the same traversal costs O(V²), because each row has V cells.
61. How do you check if a graph can be colored with two colors so that no edge connects equal colors?
Correct answer: BFS or DFS, giving neighbors the opposite color
Such a graph is bipartite. A conflict means there's an odd cycle, and then two colors aren't enough. Typical problem: split people into two teams where rivals end up in different teams.
62. What does
x & (x - 1)do for a positive integerx?Correct answer: Clears the lowest set bit (0 only for powers of two)
Subtracting 1 flips the lowest 1 and the zeros below it; AND removes that bit. So
x & (x - 1) === 0checks for a power of two, and repeating it counts the set bits.63. Every number in an array appears twice except one. How do you find it in O(n) time and O(1) memory?
Correct answer: XOR all numbers: pairs cancel, the single one remains
a ^ a = 0anda ^ 0 = a, and XOR is commutative, so pairs vanish in any order. Sorting is O(n log n); a map is O(n) time but O(n) memory.64. What is the complexity of this function?
function f(n) { if (n <= 1) return 1; return f(n / 2) + f(n / 2); }Correct answer: O(n)
Each call makes two calls on half the input, so the call tree has 1 + 2 + 4 + ... + n ≈ 2n nodes with O(1) work each. If it made one call,
f(n / 2)alone, it would be O(log n).65. Which algorithm finds a minimum spanning tree by adding the cheapest edges that don't create a cycle?
Correct answer: Kruskal's algorithm
Kruskal sorts edges by weight and uses union-find to skip edges that would connect vertices already in the same component. Dijkstra computes shortest paths, which is a different problem.
66. Why does the order of keys in a JavaScript object not always match insertion order?
Object.keys({ b: 1, 2: 1, a: 1, 1: 1 });Correct answer: Integer-like keys go first in ascending order, then the rest
The result is
["1", "2", "b", "a"]. If you need a dictionary with predictable insertion order for any keys, useMap.67. What is the complexity of checking whether two strings of length n are equal?
Correct answer: O(n) in the worst case
Characters are compared until a difference is found, so equal or nearly equal strings cost O(n). This matters when strings are used as keys: hashing a key also reads the whole string.
68. Which problem is solved by keeping the k most recent values in a fixed-size ring buffer?
Correct answer: Keeping the last k events, like recent logs or a moving average
A ring buffer overwrites the oldest entry when it's full, with O(1) writes and no shifting. The k largest values need a heap, not a ring buffer.
69. What is the "meet in the middle" idea in two-sided BFS?
Correct answer: Search from start and target at once until they meet
If each step branches b ways and the distance is d, one BFS explores about bᵈ states, two searches about 2 × b^(d/2). It's used in puzzles such as "word ladder".
70. Why are arrays usually faster to iterate than linked lists even though both are O(n)?
Correct answer: Array items sit together in memory, which suits the CPU cache
Big O hides constants. Contiguous memory is prefetched in cache lines; list nodes scattered around the heap cause cache misses. That's why arrays win in practice for most workloads.
71. What is the time complexity of
str.split("").sort().join("")for a string of length n?Correct answer: O(n log n)
Splitting and joining are O(n), but sorting the characters is O(n log n), which dominates. For short words it doesn't matter; for long strings counting characters is O(n).
72. What does this function do, and what is its complexity?
function f(nums) { const seen = new Set(nums); let best = 0; for (const x of seen) { if (seen.has(x - 1)) continue; let len = 1; while (seen.has(x + len)) len++; best = Math.max(best, len); } return best; }Correct answer: Longest run of consecutive numbers, O(n)
A run is counted only from its smallest number (when
x - 1is missing), so every number is checked in the inner loop at most once. Sorting would give O(n log n).73. What does it cost to insert a value into a sorted array and keep it sorted?
Correct answer: O(n): finding the spot is O(log n), but shifting elements is O(n)
Binary search finds the position quickly, but
splicestill moves every later element. For many inserts with lookups in between, a balanced tree or a heap (depending on the queries) is a better fit.74. How do you rotate an array right by k positions in place with O(1) extra memory?
// [1, 2, 3, 4, 5, 6, 7], k = 3 -> [5, 6, 7, 1, 2, 3, 4]Correct answer: Reverse the whole array, then reverse the first k and the rest
Three reversals put every element in place in O(n) time and O(1) memory.
unshift(pop())is O(n) per step, so O(n × k) in total, and copying needs O(n) memory. Usek % nfor k larger than the length.75. Subset sum: can some of the numbers add up to
target? What is the classic DP solution?Correct answer: A boolean table of reachable sums, updated for each number: O(n × target)
reachable[s]says whether sumscan be formed; for each number, update sums from high to low so it's used once. Greedy can miss solutions, and permutations are O(n!). The DP is pseudo-polynomial: fast only whiletargetis small.