Volume 1 Exercises: Foundations of ComputingPractice for Volume 1
0 / 0

Workbench / Volume 1 Exercises: Foundations of Computing

V1·04

Algorithms

Exercises for Volume 1, chapter 04: complexity analysis (Big-O, Ω, Θ, growth classes, best/average/worst, amortised, time–space trade-offs), searching, sorting (properties, the classic algorithms, what libraries use), recursion and memoisation, divide and conquer, dynamic programming, greedy algorithms and exchange arguments, graph algorithms (BFS, DFS, cycles, topological sort, Dijkstra, Bellman–Ford, Floyd–Warshall, A*, MSTs, SCCs), and string algorithms (KMP, Z, Rabin–Karp, Aho–Corasick). 13 theory questions, 11 programming exercises, 3 cumulative projects with chapters 01–03, the concepts the chapter leaves out, and 6 senior-level exercises.

40 exercises · ~15 min to read
Updated Suggest a correction

Start here: how this chapter's exercises work

Same four sets and the same locking. Programming solutions show real output (Java 21, Python 3.13). For algorithms, the most useful numbers are counts (comparisons, calls) and growth (what happens when n doubles), which don't depend on your machine; timings are included where the effect is large.

Coverage map.

Chapter component Exercises
what we measure; Big-O, Ω, Θ; growth classes T1, T2
best, average and worst case; input shape T3, P3
amortised analysis; time–space trade-offs; analysing code T2, T4
linear, binary and interpolation search T5, P1
sorting properties (stable, in-place, adaptive); insertion, selection, bubble, merge, quick, heap sort T6, P2, P3, P4
counting, radix and bucket sort; what libraries use; cache and parallelism T7, P4
recursion trees, memoisation, tail recursion and stack depth T8, P5
divide and conquer T8, P2
dynamic programming: substructure, top-down vs bottom-up, state, transitions, reconstruction T9, P5, P6
greedy algorithms, exchange arguments, when greedy fails T10, P5, P9
BFS, DFS, cycle detection, topological sort T11, P8
shortest paths: Dijkstra, Bellman–Ford, Floyd–Warshall, A*; MSTs; SCCs T11, T12, P7
string matching: naive, KMP, Z, Rabin–Karp, Aho–Corasick T13, P10
regular expressions and backtracking (gaps) P11, S3

Theory

T1. What Big-O does and doesn't say

  1. Define O, Ω and Θ in plain words, and explain why "binary search is O(n)" is true but useless.
  2. Rank, from slowest-growing to fastest: n log n, 2ⁿ, log n, n², 1, n, n!, √n. For n = 1 million, roughly how many operations is each (where it's computable)?
  3. Give two reasons an O(n²) algorithm can beat an O(n log n) one in practice, using P2's measurements.

T2. Analysing code you'll actually see

Give the time complexity of each, in terms of n (orders) and m (items per order), and say which you'd flag in code review:

  1. For each order, check processedIds.contains(order.id) where processedIds is a List.
  2. The same with a HashSet.
  3. Build a CSV line by line += field + "," for m fields, for each of n orders.
  4. Sort the orders, then for each order binary-search a sorted price list of size p.
  5. A loop for (int i = 1; i < n; i *= 2).
  6. Nested loops comparing every pair of orders to find duplicates.

T3. Best, average and worst case, and who picks the input

  1. Explain best, average and worst case for quicksort with a "first element as pivot" rule. What input triggers the worst case, and how common is that input in real systems? Use P3's comparison counts.
  2. Why do library implementations use random pivots, median-of-three, or introsort (switching to heapsort when recursion gets too deep)?
  3. Why must you assume the worst case when an attacker chooses the input?

T4. Amortised analysis and time–space trade-offs

  1. Explain "amortised O(1)" using a dynamic array (chapter 03's T3) and a second example: a queue built from two stacks. Why is amortised O(1) not good enough for a hard real-time system?
  2. Give three time–space trade-offs from everyday systems (caching, precomputation, indexes) and the cost each pays.

T5. Searching sorted data

  1. Why does binary search need sorted data and random access, and how many steps does it take for 1 billion elements?
  2. Arrays.binarySearch on {900, 930, 930, 930, 1015, 1200} for 930 returned index 2. Why is that a problem for "find the first order at 9:30", and what's the fix?
  3. The midpoint (lo + hi) / 2 contained a bug for nine years in the JDK's own binary search (reported in 2006). What's the bug and the two standard fixes?
  4. When can interpolation search beat binary search, and when is it worse?

T6. Sorting algorithms and their properties

  1. Define stable, in-place and adaptive. Why does stability matter when you sort orders by time and then by kitchen?
  2. Fill in, for insertion, selection, bubble, merge, quick and heap sort: best, average and worst time; extra memory; stable or not.
  3. Which algorithm would you choose for (a) nearly sorted data, (b) linked lists, (c) a guaranteed O(n log n) with O(1) extra memory, (d) data larger than RAM?

T7. Beating n log n, and what libraries really use

  1. Why can't any comparison sort beat Ω(n log n) in the worst case? (Sketch the decision-tree argument.)
  2. How do counting sort and radix sort avoid that limit, and when are they practical? Give a TiffinBox example.
  3. What do Java's Arrays.sort(int[]), Arrays.sort(Object[])/List.sort, and Python's sorted use, and why does Java use different algorithms for primitives and objects?

T8. Recursion, memoisation and divide and conquer

  1. Draw the recursion tree for naive fib(5), count the calls, and explain why naive fib(30) makes 2,692,537 calls (P5) while the memoised version makes 31.
  2. State the divide-and-conquer pattern and give the recurrence for merge sort. Solve it with the recursion-tree method (or the master theorem).
  3. Why don't Java and Python optimise tail calls, and what do you do instead when recursion depth could be large?

T9. Designing a dynamic program

For each problem, define the state, the transition (recurrence), the base cases, the answer's location and the time and memory cost; then say how you'd reconstruct the actual solution, not just its value:

  1. Fewest coins (or notes) to make an amount from a set of denominations.
  2. Edit distance between a typed dish name and a menu item (for "did you mean…?").
  3. Delivery bag packing: choose dishes (each with a weight and a value) to maximise value within a weight limit (0/1 knapsack).

T10. Greedy algorithms: when they're right and when they fail

  1. Why does "take the largest note first" give the fewest notes for Indian currency (₹1, 2, 5, 10, 20, 50, 100, 200, 500) but not for coins {1, 3, 4}? Use P5's results.
  2. A rider can do one delivery at a time; each delivery is a time interval. To maximise the number of deliveries, which greedy rule is correct: earliest start, shortest duration, or earliest finish? Prove it with an exchange argument, and give counterexamples for the other two (P9).
  3. Name three classic greedy algorithms that are provably optimal.

T11. Traversals, cycles and ordering

  1. Compare BFS and DFS: data structure used, order of visiting, memory, and one problem each solves best.
  2. How does DFS detect a cycle in a directed graph (three colours), and why isn't "I've seen this node before" enough?
  3. Explain topological sort with Kahn's algorithm, and how it reports a cycle. Give three everyday uses (P8).
  4. What is a strongly connected component, and where might you need SCCs in a backend system?

T12. Choosing a shortest-path algorithm

For each situation, choose BFS, Dijkstra, Bellman–Ford, Floyd–Warshall or A*, and justify it with the algorithm's assumptions and cost:

  1. Fewest transfers on a metro map.
  2. Fastest delivery route by travel time on a city road network (non-negative times), from one kitchen.
  3. The same, but you have coordinates and want to search towards the destination faster.
  4. Route costs that include a cashback (a negative cost) on some partner roads.
  5. Distances between all 200 kitchens and all 200 others, computed nightly.

Explain, using P7, exactly why Dijkstra gives a wrong answer with a negative edge.

T13. String matching

  1. Why can naive substring search take O(nm) comparisons, and which inputs trigger it? P10 measured it.
  2. How does KMP's prefix function avoid re-examining text characters? What does the table hold for the pattern abab?
  3. What does Rabin–Karp's rolling hash make easy that KMP doesn't? What's its weakness?
  4. You must scan every chat message for any of 5,000 banned words. Which algorithm, and why not 5,000 separate searches?

Programming exercises

P1. Binary search done right

In Java, write lowerBound(long[] a, long key) returning the first index with a[i] >= key. Test on {900, 930, 930, 930, 1015, 1200} with keys 930 and 1000, and compare with Arrays.binarySearch. Print (lo + hi) / 2, lo + (hi - lo) / 2 and (lo + hi) >>> 1 for lo = 1,500,000,000 and hi = 2,000,000,000. Count the steps of a binary search over 1 billion values.

P2. Where O(n²) beats O(n log n)

Implement insertion sort and a top-down merge sort for int[] in Java. Time both (averaged over many repetitions, after a warm-up round) for n = 16, 64, 256, 4,096 and 65,536 on random data. Find the crossover and explain it.

P3. Quicksort's worst case, counted

Implement quicksort with the first element as pivot (recursing on the smaller side and looping on the larger, so the stack depth stays O(log n)). Count comparisons for 20,000 random integers and for 20,000 already-sorted integers. Compare with n²/2.

P4. Stability and comparator contracts

  1. Sort five orders by time, then stably by kitchen, and print them.
  2. Sort 100,000 random Integers with the comparator (x, y) -> x - y, and check whether the result is sorted; then shuffle and sort 2,000 random integers 50 times with it. What happens, and why?

P5. Memoisation, coins and when greedy fails

In Python: (1) count calls of naive fib(30) and of a memoised version (functools.lru_cache); (2) implement greedy change-making and DP change-making with reconstruction, and compare them for ₹388 with Indian denominations, 6 with {1, 3, 4}, and 14 with {1, 7, 10}.

P6. "Did you mean…?" with edit distance

Implement edit distance with dynamic programming, and use it to suggest the closest menu item (biryani, paneer tikka, pesarattu, pongal, pav bhaji, dosa, idli) for the queries biriyani, panner tika, dosaa and pizza. What should the system do for pizza?

P7. Dijkstra, a negative edge, and Bellman–Ford

Implement Dijkstra (with a binary heap and a "done" set) and Bellman–Ford in Python. Run Dijkstra on roads Kitchen→A (4), Kitchen→B (1), B→A (2), B→C (5), A→C (1). Then run both on Kitchen→A (2), Kitchen→B (5), B→A (−4), A→C (3), and explain the difference.

P8. Ordering kitchen tasks, and catching a cycle

Model the delivery workflow as dependencies: cook needs buy groceries and prep; prep needs buy groceries; pack needs cook; deliver needs pack and assign rider. Produce a topological order with Kahn's algorithm (processing ready tasks alphabetically, for a deterministic result). Then add "buy groceries needs deliver" and report the cycle.

P9. Greedy scheduling, proved and broken

For a single rider, implement interval scheduling with three greedy rules (earliest finish, earliest start, shortest duration). Run them on slots A 9–11, B 10–12, C 11–13, D 12–14, E 8–17, F 13–15, and on P 9–13, Q 12–14, R 13–17. Explain which rule is right with an exchange argument (T10).

P10. Searching an adversarial text

Implement naive substring search and KMP, counting character comparisons. Search for "a" * 999 + "b" in "a" * 100_000. Then compute KMP's prefix function for abab and aabaaab by hand and check it with your code.

P11. A regular expression that takes forever

In Python, time re.match(r'^(a|aa)+$', 'a' * n + '!') for n = 24, 28 and 32. Then try the same pattern in Java. Explain the growth, why the two engines differ, and how you'd write the pattern safely.

Cumulative projects (chapters so far: 01–04)

C1. A "top customers" report that scales

Write a Java command-line program that reads order lines customerId,paise from standard input (potentially 100 million lines), and prints the top K customers by total spend (K from an argument), with ties broken by customer ID. Requirements: exact long totals with overflow checks; a heap of size K for the top-K step; malformed lines to stderr with line numbers; exit codes as in earlier chapters. Measure time and memory for 10 million lines with 1 million distinct customers, then answer: what changes when the number of distinct customers no longer fits in memory?

Combines: streams, exit codes, buffering (ch 01); parsing, error handling, comparator contracts, overflow (ch 02); hash maps and their memory, heaps (ch 03); top-K, sorting, complexity analysis, external algorithms (ch 04).

C2. Route planner with a choice of algorithm

Extend chapter 03's C2 routing program with weighted edges (minutes) and a command-line flag choosing --bfs (fewest hops), --dijkstra, or --astar (using straight-line distance from coordinates in the input, divided by the maximum speed). For each query, print the route, its total minutes, and how many nodes the algorithm popped from its queue. Verify on random queries that Dijkstra and A* always return the same total, and compare their popped-node counts. Reject edges with negative weights at load time with a clear error and exit code.

Combines: arguments, files, stderr and exit codes (ch 01); sealed types or an interface for the strategy, records, error handling (ch 02); adjacency arrays, priority queues, memory (ch 03); BFS, Dijkstra, A*, admissible heuristics, and verification by differential testing (ch 04).

C3. Fuzzy dish search over a real menu

Write a small search service (a Java program reading a menu file and then queries from stdin) that returns, for each query, the best matches using: exact prefix matches from a trie first, then edit-distance matches within a length-dependent threshold, ranked by distance and then popularity. Normalise text (case folding with Locale.ROOT, trimming, collapsing spaces) and accept Unicode dish names. Measure the time per query for a 10,000-item menu, then optimise the fuzzy step so it doesn't compute edit distance against every item (for example, only items whose length is within the threshold, or a BK-tree). Verify the optimised version returns exactly the same results as the brute force on 10,000 random queries.

Combines: stdin and encodings (ch 01); strings, locale-independent operations, testing (ch 02); tries, hash maps (ch 03); edit distance DP, pruning, complexity and differential testing (ch 04).

What the chapter leaves out

Benchmarking without fooling yourself

Every timing in these exercises was taken carefully (warm-up rounds, repetitions), and still the numbers vary. Professional measurement on the JVM uses JMH (the Java Microbenchmark Harness), because naive timing is fooled by: JIT warm-up (chapter 01's S7), dead-code elimination (if a result isn't used, the JIT may delete the work: always consume results), constant folding, on-stack replacement, garbage-collection pauses, CPU frequency scaling and noisy neighbours. Report distributions (median, p99), not single numbers, and compare against a baseline in the same run. Python's timeit and pyperf play the same role. Measure on production-like data: input shape changes results as much as size (P3).

Comparators and total orders

Sorting, binary search, TreeMap and priority queues all assume the comparison is a total order: consistent, transitive and antisymmetric. Broken comparators are a common production bug: subtraction overflow (P4), doubles with NaN (NaN < x and NaN > x are both false; use Double.compare), comparators that read mutable fields, and comparators inconsistent with equals (a TreeSet will treat "equal-comparing" distinct objects as duplicates and silently drop one). Build comparators from Comparator.comparing(...).thenComparing(...), and give every sort a deterministic tie-breaker (often the ID), or results will vary between runs.

NP-hard problems, heuristics and approximation

Several everyday business problems have no known efficient exact algorithm: assigning many deliveries to riders with time windows (vehicle routing), packing (knapsack with large weights, bin packing), scheduling with constraints, and the travelling salesman problem. They're NP-hard: exact solutions take exponential time in the worst case. Senior engineers recognise these early and choose deliberately: exact solvers for small instances (integer linear programming, constraint solvers such as Google OR-Tools or Timefold), approximation algorithms with proven bounds, and heuristics (greedy construction followed by local search: 2-opt swaps, simulated annealing) that give good-enough answers fast. The trap is spending weeks trying to make an exact algorithm fast for a problem that can't have one.

Algorithms for data that doesn't fit, or doesn't stop

The chapter's algorithms assume the data fits in memory. Real systems also need external algorithms (external merge sort; hash partitioning, as in C1; the database's sort and hash joins spilling to disk) and streaming algorithms that see each item once with bounded memory: reservoir sampling (a uniform random sample of k items from a stream of unknown length; measured: choosing 3 of 10 items 100,000 times picked each item about 30,000 times, as expected), count-min sketch (approximate frequencies), HyperLogLog (approximate distinct counts in a few KB; Redis's PFCOUNT), and t-digest (approximate percentiles for latency monitoring). These power analytics and observability systems.

Regular expressions are algorithms too

Developers write regular expressions daily without thinking of them as algorithms, but backtracking engines (Java, Python, JavaScript, PCRE) have exponential worst cases for ambiguous patterns (P11), and the input often comes from users. Know which engine you use, prefer linear-time engines (RE2, Rust's regex, Go) for untrusted input, avoid nested quantifiers, bound input size, and test patterns against adversarial inputs (S3).

Randomised algorithms and adversaries

Randomness is a tool, not just for simulations: random pivots make quicksort's worst case improbable for any input (T3); randomised hashing defeats hash flooding (chapter 03); random sampling estimates answers over huge data; random jitter in retries prevents synchronised retry storms. The counterpart is the adversary: whenever input comes from outside, ask what the worst input does to your algorithm, because someone may send it on purpose.

Senior exercises

S1. The endpoint that got slow as the business grew

GET /kitchens/{id}/report was 80 ms at launch and is now 9 seconds for the largest kitchens; it's fine for small ones. The code loads the kitchen's orders, then for each order loops over all of the kitchen's menu items to find the dish, then over all promotions to find any that applied, then builds the response with string concatenation. Describe how you'd find the cause with evidence (not guessing), estimate the complexity from the description, propose fixes in priority order, and say how you'd prevent the regression class.

S2. A sort that crashes in production but not in tests

A ranking service sorts dishes with this comparator, and production logs show occasional IllegalArgumentException: Comparison method violates its general contract! (tests never fail):

Java
(a, b) -> {
    if (a.isSponsored() != b.isSponsored()) return a.isSponsored() ? -1 : 1;
    double diff = b.score() - a.score();
    return diff > 0 ? 1 : diff < 0 ? -1 : (int) (Math.random() * 3) - 1;
}

Find every reason it violates the contract, explain why it fails only sometimes and only with larger lists, fix it, and explain how you'd test comparators in general.

S3. A validation regex in a public API

Your sign-up API validates email addresses with ^([a-zA-Z0-9]+[._-]?)*[a-zA-Z0-9]+@([a-zA-Z0-9]+\.)+[a-zA-Z]{2,}$. A security scanner flags it. Explain the risk from P11, construct an input that makes it slow (and measure it in Python), and design the fix: what validation to do instead, and the general rules you'd add to the team's code review checklist for regexes.

S4. Recognising an NP-hard problem in a feature request

Product wants "assign tonight's 3,000 deliveries to 400 riders so total travel time is minimal, respecting each customer's delivery window and each rider's shift". A colleague proposes an exact algorithm "trying all assignments, with pruning". Explain why that won't work, what kind of problem this is, and write a short proposal for a practical approach: what you'd build first, how you'd measure quality without knowing the optimum, and what you'd say to product about guarantees.

S5. Make it deterministic

Five different jobs in your system produce slightly different outputs on each run given the same input: a nightly ranking (ties in score), a report exported as JSON (map iteration), a build that orders steps from a dependency graph, a sampled analytics job (random sampling), and a parallel stream that sums double revenue. For each, explain the source of non-determinism (from chapters 02–04), whether it's a bug, and how to make the output reproducible. Then write a one-paragraph team guideline.

S6. Teach complexity with evidence

You're asked to run a 30-minute session for four junior engineers on "why complexity matters". Design it around one live experiment from this chapter (choose and justify it), the three ideas they should leave with, a short exercise they do during the session, and how you'll check they understood (not "any questions?").