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

Workbench / Volume 1 Exercises: Foundations of Computing

V1·03

Data Structures

Exercises for Volume 1, chapter 03: the cost model, arrays and dynamic arrays, cache locality, linked lists, stacks, queues, ring buffers, deques and priority queues, hashing and hash tables, trees (BSTs, AVL, red-black, B-trees, B+ trees, tries, radix trees), heaps, graphs, and advanced structures (union-find, segment and Fenwick trees, Bloom filters, skip lists, LSM trees, Merkle trees). 14 theory questions, 12 programming exercises, 3 cumulative projects with chapters 01–02, the concepts the chapter leaves out, and 7 senior-level exercises.

43 exercises · ~16 min to read
Updated Suggest a correction

Start here: how this chapter's exercises work

Same four sets and the same locking as the earlier chapters: write 60 characters of your own answer to unlock hint 1, 40 more for hint 2, and 40 more plus two minutes for the solution. Programming solutions show real output (Java 21, Python 3.13, SQLite, Linux). Timings depend on the machine; ratios and shapes (which is faster, how it grows) are the point.

Coverage map.

Chapter component Exercises
what a data structure is; abstract operations vs real machines; the complexity cheat sheet T1, T2, P1
arrays: contiguous memory, O(1) indexing, insertion cost, multi-dimensional T2, P1
dynamic arrays and amortised growth T3, P2
cache locality T2, P1, S3
linked lists (singly, doubly, sentinels, circular, intrusive); when to use them T4, P1
stacks, queues, ring buffers, deques T5, P3
priority queues and binary heaps T6, P7
hash functions, collisions, load factor, chaining, open addressing T7, P4, S1
the equality and hash contract; iteration order T7, P5, S6
trees: terminology, traversals, BSTs T8, P6
balancing: rotations, AVL, red-black T8, P6
B-trees, B+ trees and databases T9, P12, S4
tries and radix trees T10, P8
graphs: terminology, matrix vs list T11, P9
union-find, segment trees, Fenwick trees T12, P10
Bloom filters, skip lists, LSM trees, Merkle trees T13, P11, S5
choosing a data structure T14, C1, S3

Theory

T1. Which operation, how often, on how much?

For each everyday feature, name the operations it needs most, their frequency, and the structure you'd choose (with its costs):

  1. "Recently viewed" dishes in an app: show the last 10, newest first.
  2. Checking whether a coupon code has already been used, among 50 million used codes.
  3. A leaderboard of the top 100 delivery riders by rating, updated on every delivery.
  4. Showing a kitchen's orders sorted by delivery time, with frequent inserts and range queries ("between 12:00 and 13:00").
  5. An undo history for a text editor.

T2. Why "O(1)" and "O(n)" don't tell the whole story

Explain why ArrayList beats LinkedList even for inserting in the middle of a large list, although textbook complexity says linked lists insert in O(1). Use the ideas of finding the position, cache lines and memory overhead per element. Then explain why indexing an array is O(1) from first principles (what the CPU computes).

T3. Amortised growth

A dynamic array doubles its capacity when full. Prove that appending n elements costs O(n) in total, so O(1) amortised per append. Then explain why growth by a constant amount (+10 slots) would be O(n²) in total, why real implementations use factors like 1.5 (Java) or about 1.125 (Python), and when you should call ensureCapacity or pass an initial capacity.

T4. When a linked list is the right answer

Give three situations where a linked structure is genuinely the best choice, and explain what a sentinel node and an intrusive list are and why the Linux kernel uses the latter. Then explain why Java's LinkedHashMap combines a hash table with a doubly linked list.

T5. Stacks, queues, ring buffers and deques in everyday systems

For each, explain which structure is used and why: the call stack; the browser's back button; a print queue; keyboard input buffering in an OS; a bounded "last 1,000 log lines" buffer; a work-stealing thread pool (Java's ForkJoinPool). Then explain how a ring buffer works with a fixed array and two indices, and how it distinguishes "full" from "empty".

T6. Heaps and priority queues

  1. Explain how a binary heap stored in an array finds a node's parent and children, and why insert and remove-min are O(log n) while peek is O(1).
  2. You need the 10 largest orders out of 5 million. Compare sorting everything with a heap of size 10. Which heap: min-heap or max-heap, and why?
  3. Why can't a binary heap efficiently answer "change this rider's priority" without help, and what is added to make it possible?

T7. Inside a hash table

  1. Explain how a hash table turns a key into a slot, what a collision is, and the two main ways of handling them (separate chaining, open addressing with linear probing).
  2. What is the load factor, and why does linear probing degrade sharply above about 0.75? Use the chapter's measured probe counts.
  3. Why does Java's HashMap turn long chains into red-black trees, and why does that only help if the keys are Comparable? (P4 measures it.)
  4. Why is iterating a HashMap in "random" order, and why must you never depend on that order?

T8. Binary search trees and balancing

  1. State the BST property and explain why lookup is O(height).
  2. What happens to a naive BST when keys arrive in sorted order (order IDs, timestamps)? P6 measured it.
  3. Explain what a rotation does and how AVL and red-black trees use rotations to keep height O(log n). Which keeps the tree more strictly balanced, and which does Java's TreeMap use?
  4. Name the three depth-first traversal orders and one everyday use of each.

T9. B-trees, B+ trees and why databases use them

  1. Why do databases and file systems use B-trees with hundreds of keys per node instead of binary trees? Answer in terms of disk or page reads.
  2. What does a B+ tree add, and why does it make range queries (WHERE delivered_at BETWEEN …) fast?
  3. How many levels does a B+ tree need for 1 billion rows with 500 keys per node?
  4. Why does a composite index on (kitchen_id, delivered_at) help WHERE kitchen_id = 7 AND delivered_at > … but not WHERE delivered_at > … alone?

T10. Tries and radix trees

Explain how a trie stores strings and why lookup and prefix search cost O(length of the key), independent of how many keys are stored. Give three everyday uses. Then explain what a radix tree compresses and where you'll meet one (routers, HTTP routing in web frameworks, Linux's page cache).

T11. Graphs: representing a delivery network

TiffinBox has 20,000 road junctions and about 60,000 roads. Compare an adjacency matrix and an adjacency list for memory, "is there a road between A and B?", and "list all roads from A". Which suits this network, and when would you choose the other? Then explain why BFS finds the fewest hops but not the shortest distance in kilometres.

T12. Union-find, segment trees and Fenwick trees

  1. Explain union-find with path compression and union by rank, and why its operations are "almost O(1)" (inverse Ackermann). Give two everyday uses.
  2. A dashboard needs "total orders between day L and day R" for any range, with daily counts updated live. Compare a plain array, a prefix-sum array, a Fenwick tree and a segment tree.

T13. Probabilistic and storage-oriented structures

Explain in a few sentences each, with an everyday system that uses it:

  1. A Bloom filter: what it can and can't answer, and how false positive rate depends on bits per item.
  2. A skip list: how it achieves O(log n) search with randomness instead of rotations.
  3. An LSM tree: why write-heavy databases use it, and what compaction and write amplification are.
  4. A Merkle tree: how two machines find which parts of a large dataset differ by exchanging only a few hashes.

T14. Choosing, with numbers

For a service holding 10 million active delivery addresses in memory, keyed by a 64-bit customer ID, estimate the memory for (a) HashMap<Long, Address>, and (b) a sorted long[] of IDs plus a parallel array of addresses, using binary search. What do you gain and lose with (b)? When would you instead keep this in a database or a cache server?

Programming exercises

P1. ArrayList versus LinkedList, measured

In Java, fill an ArrayList<Integer> and a LinkedList<Integer> with 1 million integers. Time (after one warm-up round): iterating to sum all; 20,000 random get(i) on the ArrayList versus 2,000 on the LinkedList; 2,000 inserts in the middle; and 100,000 inserts at the front (add(0, x) on the ArrayList, addFirst on the LinkedList). Explain each result.

P2. Watch a dynamic array grow

In Python, append 200 items to an empty list and print the length at which sys.getsizeof changes, converting the size to a capacity in slots (subtract the empty list's size and divide by 8). Then, in Java, time adding 10 million Integers to new ArrayList<>() versus new ArrayList<>(10_000_000). Relate both to T3.

P3. A ring buffer for the last N log lines

Implement LastN<T> in Java with a fixed array, a start index and a size: add overwrites the oldest when full, and snapshot() returns the items oldest-first. Test with capacity 3 and seven lines, printing after 2, 3 and 7 lines. Then do the same with ArrayDeque. Finally, answer: why would a logging library prefer the fixed array?

P4. What a bad hashCode costs

Create three key classes, each with correct equals: a record (good hashCode); a class whose hashCode always returns 42 but which implements Comparable; and one with hashCode 42 that isn't Comparable. Time 20,000 puts followed by 20,000 gets in a HashMap for each (after a warm-up round). Explain the three results using T7.

P5. Iteration order, and an LRU cache in five lines

  1. Insert vada, idli, upma, dosa, poha into a HashMap, a LinkedHashMap and a TreeMap, and print each key set.
  2. Build an LRU cache of capacity 3 with new LinkedHashMap<>(16, 0.75f, true) and an overridden removeEldestEntry. Put menu:1, menu:2, menu:3, then get("menu:1"), then put menu:4. Which key was evicted, and why?

P6. A naive BST meets sorted IDs

In Python (iteratively, to avoid recursion limits), insert 4,000 keys into a naive BST in random order and in sorted order, and measure each tree's height. Compare with log₂(4,000) and the red-black bound 2 log₂(n + 1).

P7. Top 10 orders out of 5 million

Generate 5 million random order amounts (fixed seed). Find the 10 largest with a PriorityQueue used as a min-heap of size 10, and by sorting a copy. Check both agree and time them (second round).

P8. Autocomplete with a trie

Implement a trie in Python (or Java) with add(word) and complete(prefix, limit) returning up to limit words in alphabetical order. Load paneer tikka, paneer butter masala, pav bhaji, pesarattu, poha, pongal, palak paneer, papad, and test prefixes pa, pan and x.

P9. A sparse road network and BFS

Generate a random graph of 20,000 junctions where each junction gets roads to 3 random others (undirected). Store it as an adjacency list, run BFS from junction 0 to 19,999, and print the number of hops. Compute what an adjacency matrix would need.

P10. Merge duplicate customer accounts with union-find

Six accounts list identifiers: A1 {98765, asha@x.in}, A2 {asha@x.in}, A3 {91234}, A4 {91234, ravi@y.in}, A5 {98765}, A6 {zoya@z.in}. Accounts sharing any identifier belong to the same customer (transitively). Implement union-find with path compression and print the groups.

P11. A Bloom filter, checked against the formula

Implement a Bloom filter with m bits and k hash positions derived from one SHA-256 digest (double hashing: index_i = (a + i·b) mod m). Add 100,000 email addresses; test 100,000 different ones; compare the measured false positive rate with (1 − e^(−kn/m))^k for 8 and 10 bits per item, using k = round((m/n) ln 2). Confirm there are no false negatives.

P12. A B+ tree in a real database

In Python with SQLite, create orders(id integer primary key, phone text, paise int) with 500,000 random rows. Show EXPLAIN QUERY PLAN for SELECT count(*) FROM orders WHERE phone = ?, time it, create an index on phone, and show the plan and timing again. Explain both plans in terms of T9.

Cumulative projects (chapters so far: 01–03)

C1. A command-line "seen before?" filter

Write a Java tool Seen that reads lines (for example, order IDs or coupon codes) from standard input and writes to standard output only the lines it hasn't seen before, like sort -u but keeping the original order and streaming. Options (as arguments): --exact uses a HashSet<String>; --approx N P uses a Bloom filter sized for N items at false positive rate P. Report to standard error at the end: lines read, lines output, approximate memory used. Exit 0, or 2 if any input line was empty. Test it with seq 1 1000000 | sed 's/^/order-/' piped through sort -R (shuffle) and duplicated, and compare memory and output counts between modes.

Combines: stdin/stdout/stderr, arguments, pipes, exit codes (ch 01); parsing arguments, error handling, closures or interfaces for the two modes (ch 02); hash sets, Bloom filters, memory overheads (ch 03).

C2. Delivery routing service, end to end

Write a Java program that reads a road network from a file given as an argument (lines from,to,metres), builds an adjacency list using records for edges, and answers queries from standard input (from to) with the fewest-hops route using BFS, printing the path. Handle: unknown junctions (message on stderr, continue), unreachable destinations, malformed lines (line number on stderr), and exit codes (0 success, 2 if any query failed, 1 if the file couldn't be read). Store the network so that 1 million junctions and 3 million roads fit in a 512 MB heap: estimate your memory per junction and per road before writing the code.

Combines: files, paths, arguments, stdin/stderr, exit codes (ch 01); records, error handling, iteration over recursion, primitive vs boxed types (ch 02); graphs, BFS, queues, memory overheads, choosing structures (ch 03).

C3. A sorted index you can trust

Write a Java class SortedIndex that stores (deliveryTime, orderId) pairs and answers "orders between T1 and T2" for a kitchen dashboard. Implement it twice: (a) with TreeMap<Long, List<Long>> and subMap; (b) with sorted parallel long[] arrays rebuilt in bulk, using binary search for the range bounds. Write a property test in plain Java (or with jqwik) that generates 10,000 random datasets and queries and checks both implementations against a brute-force scan. Include duplicate times, empty ranges, T1 > T2, and the extreme values Long.MIN_VALUE/Long.MAX_VALUE. Measure memory and query time for 1 million entries.

Combines: exit codes for the test runner (ch 01); integer overflow in midpoint calculations, testing with generated inputs, invariants (ch 02); balanced trees, arrays, binary search, memory estimation (ch 03).

What the chapter leaves out

Memory overhead of convenient collections

Big-O hides constant factors, and in Java the biggest constant is object overhead. Every object has a header (12–16 bytes on 64-bit JVMs), fields are padded to 8 bytes, and generic collections hold boxed values. Measured: 1 million int → int entries in a HashMap<Integer, Integer> took about 73 bytes per entry, while two plain int[] arrays need exactly 8 bytes per entry: about 9× less. At millions of entries, this decides whether a service fits in its container (chapter 01's S6). Remedies: primitive collections (fastutil, Eclipse Collections, HPPC), arrays and parallel arrays (data-oriented design, chapter 02), compact encodings (IDs as int rather than String), and measuring with a heap profiler or JOL (Java Object Layout).

Concurrent data structures

The chapter's structures are single-threaded. Shared between threads without care, they break: Java 7's HashMap could even form an infinite loop during a concurrent resize, and current versions can silently lose entries. Production code uses structures designed for concurrency: ConcurrentHashMap (lock striping and CAS per bin), ConcurrentSkipListMap (a sorted map without global locks), CopyOnWriteArrayList (for read-mostly lists), ArrayBlockingQueue/LinkedBlockingQueue for producer–consumer pipelines, and LongAdder for counters (chapter 02's S4). Compound operations still need care: if (!map.containsKey(k)) map.put(k, v) is a race even on a ConcurrentHashMap; use putIfAbsent or computeIfAbsent.

Hash flooding and randomised hashing

If attackers can choose keys and predict the hash function, they can make every key collide. Java's String.hashCode is deterministic, and colliding strings are easy to build: "Aa" and "BB" have the same hash, so all 16 strings made of four such blocks (AaAaAaAa, AaAaAaBB, …) share one hash code (measured). In 2011, this attack (on request parameters parsed into hash tables) could stall many web frameworks with a single request. Defences: tree bins with Comparable keys (Java 8+, P4), randomised hashing (Python randomises string hashes per process, so hash('idli') differs between runs unless PYTHONHASHSEED is fixed; Rust uses SipHash with random keys), and limits on the number of request parameters and JSON keys (S1).

Persistent (immutable) data structures

The chapter's structures are mutable: updates change them in place. Persistent structures return a new version on each update and keep the old one valid, sharing most of their memory (structural sharing): an update to a balanced tree copies only the O(log n) nodes on the path to the change. They make undo, snapshots, time travel debugging and safe sharing between threads cheap. Used throughout Clojure and Scala, in Java libraries such as Vavr and PCollections, in Git's object model, and in many front-end state libraries (Immer). List.copyOf (chapter 02) is the simple, O(n) version of the same idea.

Iteration order as an accidental API

Hash-based collections have unspecified iteration order, yet code and tests often depend on it by accident: JSON output whose key order changes, a test that passes on one JDK and fails on another, "first matching element" logic that picks a different element after a resize. Java's Set.of/Map.of even randomise iteration order per JVM run, to flush out such dependencies early. Rule: if order matters, choose a structure that defines it (LinkedHashMap, TreeMap, a List), and make tests compare as sets when it doesn't (S6).

Cache-friendly and succinct structures

On modern hardware, memory access patterns often matter more than operation counts (T2). Senior engineers know a few cache-aware designs: open addressing with SIMD probing (Google's Swiss tables, Rust's HashMap: they check 16 slots per instruction); B-trees in memory (beating red-black trees for large sorted sets because each node fills cache lines); struct-of-arrays layouts for analytics; and succinct or compressed structures (Roaring bitmaps, used by search engines and analytics databases for sets of integers, compress dense and sparse ranges differently and support fast intersections).

Senior exercises

S1. A single request that stalls a server

Your Java service parses JSON request bodies into HashMap<String, Object>. A security researcher reports that a 2 MB request with 50,000 specially chosen keys takes 30 seconds of CPU to parse. Explain the attack using T7 and the gaps section (generate a few colliding strings yourself), explain why modern Java mitigates it partially, and write the defence-in-depth plan: what limits and settings you'd apply at each layer.

S2. Design a production cache

The menu service gets 20,000 requests per second; the database can handle 2,000. Design an in-process cache for menus: key, value, eviction policy, size bound, expiry, invalidation when a kitchen updates its menu, behaviour under concurrency and when the cache is cold, and what you'd measure. Explain why P5's LinkedHashMap LRU isn't enough and what a library like Caffeine adds.

S3. Pick the structure for a hot path

A pricing service evaluates, for every order line, which of 3,000 active promotions apply. Each promotion has a kitchen set, a dish category set, a time window and a minimum basket value. At peak there are 50,000 order lines per second. The current implementation loops over all promotions for every line. Estimate the current cost, then design data structures that make the lookup fast, explaining the trade-offs (memory, update cost, complexity) and how you'd verify the new implementation gives exactly the same results.

S4. Index design for an orders table

The orders table (300 million rows, PostgreSQL) is queried by: (1) WHERE customer_id = ? ORDER BY placed_at DESC LIMIT 20 (order history, 5,000/s); (2) WHERE kitchen_id = ? AND status = 'PREPARING' (kitchen screens, 2,000/s; about 50 matching rows per kitchen); (3) WHERE placed_at >= ? AND placed_at < ? (nightly reports). Inserts run at 1,500/s. Propose indexes (columns, order, any partial or covering indexes), explain each with B+ tree mechanics, estimate the write cost, and say how you'd confirm the choices.

S5. A Bloom filter in front of an expensive lookup

The coupon service checks 30,000 codes per second against 200 million used codes in a database; 98% of checked codes are new (not used). The database is the bottleneck. Design a Bloom filter in front of it: size it, decide where it lives (per instance or shared), how it's built and kept up to date as codes are used, what happens on restart, and how the false-positive rate affects the database load. Explain why a plain Bloom filter can't handle "un-using" a code (refunds), and what to use if you need that.

S6. Tests that pass on one machine

After a JDK upgrade, 14 tests fail. All compare JSON output or lists built by iterating HashMaps and Set.of(...) with expected strings. Some fail only on some runs. Explain why (using T7 and the gaps section), how you'd find every place in the codebase where behaviour depends on hash iteration order, and how you'd fix the tests and the production code without hiding real bugs.

S7. Explain it to the team

A junior engineer asks in a code review why you rejected List<Order> for a lookup-by-ID that runs inside a loop over all orders, saying "it works fine in my test with 10 orders". Write the reply (under 200 words) that teaches rather than corrects: include a number from this chapter's measurements, the complexity in plain words, the fix, and a way they can check it themselves. Then write one sentence on when their version would be fine.