Algorithms
An algorithm is a pattern you recognise, not a procedure you memorise: name the pattern before coding.
The 60-second answer
Section titled “The 60-second answer”Almost every interview problem is one of a dozen patterns. Sorted input or “minimum that works” means binary search. “Contiguous subarray with a constraint” means sliding window. “All arrangements” means backtracking. “Optimal value with overlapping subproblems” means dynamic programming. “Shortest path in an unweighted graph” means BFS; “dependencies” means topological sort. Otherwise: a hash map, a heap, or sorting first.
| Signal in the question | Pattern | Typical cost |
|---|---|---|
| “Sorted”, “find target”, “minimum that works” | Binary search | O(log n) or O(n log n) |
| “Pair/triplet that sums to”, in place, palindrome | Two pointers | O(n) |
| “Longest/shortest substring or subarray with…” | Sliding window | O(n) |
| “All combinations / permutations / valid boards” | Backtracking | Exponential, pruned |
| “Minimum/maximum cost, number of ways” | Dynamic programming | O(states × transitions) |
| “Shortest path”, “levels”, “minimum steps” | BFS | O(V + E) |
| “Components”, “cycle”, “prerequisites” | DFS / topological sort | O(V + E) |
Sorting
Section titled “Sorting”Comparison sorts are bounded by Ω(n log n). Merge sort is stable, always O(n log n), and costs O(n)
space. Quick sort sorts in place, averages O(n log n), and degrades to O(n²) on pathological pivots,
which is why library sorts randomise the pivot. Counting sort is O(n + k), only for bounded keys.
Merge sort is the one to be able to write: split in half, sort each half, then merge two sorted
arrays by repeatedly taking the smaller head. Ruby’s sort and sort_by are comparison sorts.
Binary search
Section titled “Binary search”The real pattern is a monotonic predicate: “find the first x where f(x) is true”. That covers a sorted array and a range of answers — minimum capacity or speed — via a feasibility check.
def bsearch(arr, target) lo, hi = 0, arr.length - 1 while lo <= hi mid = (lo + hi) / 2 return mid if arr[mid] == target arr[mid] < target ? lo = mid + 1 : hi = mid - 1 end nilendFor “minimum capacity to ship in d days”, binary search cap in [weights.max, weights.sum],
test a greedy feasibility check, and return lo when lo == hi. The predicate is monotonic, which
is all binary search needs — the sorted array is incidental.
Two pointers and sliding window
Section titled “Two pointers and sliding window”Two pointers converge from both ends on sorted input, or move at different speeds for cycles. Sliding window keeps a contiguous range plus a summary, so each element enters and leaves once.
def longest_unique_substring(s) last_seen = {} best = left = 0 s.each_char.with_index do |ch, right| left = last_seen[ch] + 1 if last_seen.key?(ch) && last_seen[ch] >= left last_seen[ch] = right best = [best, right - left + 1].max end bestendBFS, DFS and topological sort
Section titled “BFS, DFS and topological sort”BFS explores by distance and gives shortest paths in unweighted graphs. DFS fits components, cycles and backtracking. Kahn’s topological sort repeatedly takes an in-degree-zero node; if it stalls before emitting every node, there is a cycle.
def bfs(graph, start) dist = { start => 0 } queue = [start] until queue.empty? node = queue.shift graph[node].each do |nxt| next if dist.key?(nxt) dist[nxt] = dist[node] + 1 queue << nxt end end distendArray#shift is O(n), so that BFS is O(V²) on dense graphs — say so and use an index pointer.
Backtracking and greedy
Section titled “Backtracking and greedy”Backtracking builds a candidate, recurses, then undoes the choice; pruning is what makes it pass.
Greedy is correct only when you can argue an exchange — any optimal solution can be transformed to
include the greedy choice without getting worse. Interval scheduling (sort by end time, take what
fits) is the canonical proof; coin change with [1, 3, 4] and target 6 is the canonical failure
(greedy gives 4+1+1, optimal is 3+3), which is why DP exists.
Dynamic programming
Section titled “Dynamic programming”Requires optimal substructure and overlapping subproblems. Top-down (memoisation) keeps the problem’s shape but costs stack depth; bottom-up (tabulation) avoids recursion and can be space-optimised. State, transition, base case, answer — four questions.
def coin_change(coins, amount) # O(amount * coins) time, O(amount) space dp = Array.new(amount + 1, Float::INFINITY) dp[0] = 0 (1..amount).each do |a| coins.each { |c| dp[a] = [dp[a], dp[a - c] + 1].min if c <= a } end dp[amount].infinite? ? -1 : dp[amount]endFollow-up questions
Section titled “Follow-up questions”- Why is quick sort O(n²) on sorted input, and how do you fix it?
- When do you prefer memoisation over tabulation?
- How do you prove a greedy algorithm is correct?
- Your backtracking solution times out — what can you prune?
Common traps
Section titled “Common traps”- Binary search off-by-one. Use
lo <= hiwithhi = mid - 1, orlo < hiwithhi = mid. - Sliding window over negative numbers. The shrink invariant breaks when sums can decrease.
- Greedy when DP is required. Test the counter-example before committing.
- Recursion depth. Memoised DP at n = 10⁵ raises
SystemStackError; use tabulation.