Skip to content

Algorithms

An algorithm is a pattern you recognise, not a procedure you memorise: name the pattern before coding.

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)

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.

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
nil
end

For “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 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
best
end

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
dist
end

Array#shift is O(n), so that BFS is O(V²) on dense graphs — say so and use an index pointer.

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.

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]
end
  1. Why is quick sort O(n²) on sorted input, and how do you fix it?
  2. When do you prefer memoisation over tabulation?
  3. How do you prove a greedy algorithm is correct?
  4. Your backtracking solution times out — what can you prune?
  • Binary search off-by-one. Use lo <= hi with hi = mid - 1, or lo < hi with hi = 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.