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

Workbench / Volume 1 Exercises: Foundations of Computing

V1·05

Discrete Mathematics

Exercises for Volume 1, chapter 05: sets and bitsets, relations (equivalence and order), functions and the pigeonhole principle, propositional logic, simplifying conditions and quantifiers, proof techniques, induction and loop invariants, counting (permutations and combinations), graph theory and trees, probability (conditional probability, independence, Bayes, expectation, the birthday paradox), recurrences, and Boolean algebra. 12 theory questions, 11 programming exercises, 3 cumulative projects with chapters 01–04, the concepts the chapter leaves out, and 6 senior-level exercises.

39 exercises · ~14 min to read
Updated Suggest a correction

Start here: how this chapter's exercises work

Same four sets and the same locking. Discrete mathematics is the chapter where "prove it" and "measure it" meet: most programming exercises check a formula against a simulation or an exhaustive enumeration, with real output (Python 3.13, Java 21). Where a result is a simulation, the solution gives the number of trials, since random results vary slightly between runs.

Coverage map.

Chapter component Exercises
sets, set notation, operations; bitsets T1, P1
relations; equivalence relations; order relations T2, P3
functions, domain/codomain; injective, surjective, bijective T3
the pigeonhole principle T3, P4
propositional logic; logical laws; simplifying conditions T4, P2
predicates and quantifiers T5
why proofs; proof techniques T6
ordinary, strong and structural induction; loop invariants T7, P8
counting principles; permutations; combinations T8, P9
graph theory fundamentals; trees as mathematical objects T9
sample spaces, axioms; conditional probability, independence, Bayes T10, P6, P7
random variables and expectation T10, P10
the birthday paradox and hash collisions T11, P4, P5
recurrence relations: writing and solving T12, P11
Boolean algebra, normal forms, gates, functional completeness, Boolean algebra in software T4, P2

Theory

T1. Sets everywhere in code

  1. Express each in set notation, then in Java: customers who ordered both idli and dosa; customers who ordered idli but never dosa; all permissions of a user who has two roles; whether a cashier's permissions are all included in a manager's.
  2. Why is a bitset (or EnumSet) a fast set representation when the universe is small, and what makes it unsuitable for customer IDs?
  3. How many different roles (subsets) can be built from 5 permissions? From 40? What does that imply for "test every role"?

T2. Equivalence and order relations in data

  1. State the three properties of an equivalence relation. Is "same email address, ignoring case" one? Is "prices within ₹0.10 of each other" one? (P3 checks it.)
  2. Why does it matter for equals, de-duplication and grouping that equality is an equivalence relation?
  3. State the properties of a total order and a partial order. Which is "task A must happen before task B"? Which does Comparator require?

T3. Functions and the pigeonhole principle

  1. Classify each as injective, surjective, bijective or none: a hash function from strings to 32-bit integers; a function assigning each order a unique sequence number; a function from 6-digit OTP values to users currently logging in; encryption with a fixed key.
  2. Use the pigeonhole principle to prove that any hash function from all strings to 32-bit integers has collisions, and that 2 million users with live 6-digit OTPs must share values.
  3. Why can't a lossless compressor shrink every file?

T4. Logic and Boolean algebra in code review

  1. Simplify !(a && !b) || (a && b) using De Morgan's laws, step by step. P2 checks your answer exhaustively.
  2. A refund rule reads (paid && !cancelled) || (admin && paid && !cancelled) || (admin && !paid). Simplify it, name the law you use, and check that paid && !cancelled || admin is not equivalent (find the counterexample).
  3. What are conjunctive and disjunctive normal forms, and where do you meet them (SQL WHERE clauses, feature-flag rules, SAT solvers)? Why are NAND gates "functionally complete"?

T5. Quantifiers, precisely

Translate each requirement into predicate logic with ∀ and ∃, then into code (Java streams or SQL), and state the negation in plain English:

  1. Every order in a basket has a kitchen that is open.
  2. Some rider is available within 2 km of the kitchen.
  3. For every customer there exists at least one saved address.
  4. What do allMatch and anyMatch return on an empty list, and why does that matter for requirement 1?

T6. Why programmers need proofs

  1. Name the proof techniques the chapter covers (direct, contrapositive, contradiction, cases, induction, construction) and give a one-line software example of each.
  2. Prove by contradiction that there's no largest order ID if IDs come from an auto-increment counter with no upper limit, and explain why the real system still needs to worry about the counter's type.
  3. Why isn't testing a substitute for proof, and why isn't proof a substitute for testing?

T7. Induction and loop invariants

  1. Prove by induction that 1 + 2 + … + n = n(n + 1)/2, then relate it to the cost of insertion sort's worst case.
  2. Write the loop invariant for a lower-bound binary search (lo, hi, half-open range) and prove the loop is correct using initialisation, maintenance and termination.
  3. What is structural induction, and how would you use it to argue that a recursive JSON pretty-printer terminates and visits every value?

T8. Counting, and what it means for security and testing

  1. How many 6-digit OTPs, 4-digit PINs, and 8-character passwords from 94 printable characters exist? If an attacker can try 5 OTPs per account before lockout, what's their success chance?
  2. Permutations versus combinations: ways to choose 3 toppings from 10; ways to award gold, silver and bronze among 10 riders; orders in which a rider can visit 10 addresses.
  3. A checkout form has 5 parameters with 4 possible values each. How many full combinations are there, and why can pairwise testing cover every pair of values with as few as 16 tests?

T9. Graphs and trees as mathematics

  1. State the handshake lemma and use it to prove that any graph has an even number of odd-degree vertices.
  2. State three equivalent definitions of a tree with n vertices. How many edges does it have, and why?
  3. How do these facts appear in software: a dependency graph with n packages that must be a tree; checking whether a set of n − 1 roads connects n junctions without loops; the number of comparisons in a knockout tournament?

T10. Probability that changes decisions

  1. A fraud model flags 99% of fraudulent payments and wrongly flags 1% of legitimate ones; 0.1% of payments are fraud. What fraction of flagged payments are actually fraud? Work it out with Bayes' theorem before checking P6.
  2. Two replicas each have 99% availability. Under independence, what's the chance both are down? Why is independence usually false, and what happens if they share a rack power supply? (P7.)
  3. A payment call succeeds with probability 0.7 per attempt. What's the expected number of attempts until success, and the chance of needing more than three? (P10.)

T11. The birthday paradox in identifiers and hashes

  1. Derive the approximation P(collision among n items from N values) ≈ 1 − e^(−n²/2N), and the rule "collisions become likely around √N".
  2. TiffinBox wants 6-character base-62 order codes (like aZ3k9Q) chosen at random. How many codes can it issue before the collision probability reaches 1%? 50%? What should it do instead?
  3. Why are random UUIDs (122 random bits) safe in practice, but 32-bit hash codes are not unique even for a few hundred thousand items?

T12. Recurrences from code

Write the recurrence for each and solve it (give the closed form or Θ-class):

  1. Merge sort: two halves plus a linear merge.
  2. A recursive function that processes one element and recurses on the rest, doing linear work each time (like naive insertion via recursion).
  3. Binary search.
  4. Naive Fibonacci (number of calls).
  5. A function that splits into three subproblems of size n/2 with linear combine (Karatsuba multiplication).

Programming exercises

P1. Permissions as sets and bits

Model five permissions (VIEW_MENU, EDIT_MENU, VIEW_ORDERS, REFUND, MANAGE_STAFF) as a Java enum. Give a cashier {VIEW_MENU, VIEW_ORDERS} and a manager {VIEW_MENU, EDIT_MENU, VIEW_ORDERS, REFUND} as EnumSets, and compute union, intersection, difference and the manager's complement. Then encode both as int bitmasks and test "cashier ⊆ manager" with one expression. How many distinct roles are possible?

P2. Prove a simplification by brute force

Write a Python checker that compares two Boolean functions over every combination of inputs. Use it to verify that !(a && !b) || (a && b) equals !a || b, that the refund rule from T4 simplifies to (paid && !cancelled) || (admin && !paid), and to find where paid && !cancelled || admin differs.

P3. A "nearly equal" that isn't an equivalence

Write close(x, y) = abs(x - y) < 0.1 and test transitivity with 1.00, 1.06 and 1.12. Then group the prices [1.00, 1.06, 1.12, 1.18] by "close to the first price in the group" processing in ascending and in descending order, and compare the groups. Fix it by mapping to a canonical form.

P4. Counting hash collisions

Implement Java's String.hashCode in Python (31-polynomial, 32-bit) and count how many collisions occur among 1,000,000 random 10-character strings. Compare with the birthday estimate n²/(2 × 2³²).

P5. How short can an order code be?

Compute, with the birthday approximation, the probability of at least one collision for 10,000, 100,000 and 1,000,000 random 6-character base-62 codes, and the number of codes for a 50% chance. Then verify the formula by simulation with 5-character codes (20,000 codes issued, 3,000 trials).

P6. Simulate Bayes before you trust a model

Simulate one million payments with 0.1% fraud, a detector that flags 99% of fraud and 1% of legitimate payments. Count flagged payments and how many are fraud, and compare P(fraud | flagged) with Bayes' formula. Then rerun with 2% fraud and with a 0.1% false-alarm rate, and explain what changes.

P7. Independence is an assumption

Simulate two replicas, each available 99% of the time, first with independent failures, then with a shared rack power feed that fails 0.5% of the time (taking both down) and each replica otherwise available 99.5%. Compare availabilities with the independent formula.

P8. A loop invariant you can execute

In Java, add the binary-search invariant from T7 as an assert at the top of the loop body of lowerBound, and write a buggy variant (a[mid] <= key instead of <). Run both with java -ea on {1, 3, 3, 3, 7} and key 3.

P9. Counting for security and testing

Compute, with Python's math.comb, math.perm and math.factorial: the number of 6-digit OTPs, 4-digit PINs, 8-character passwords over 94 characters; 3 toppings from 10; a podium of 3 from 10; routes through 10 addresses; full test combinations for 5 parameters × 4 values and the number of value pairs to cover; and the minimum number of users sharing an OTP when 2 million have one active.

P10. Expected retries, simulated

Simulate "retry until success" with success probability 0.7 per attempt, 200,000 times. Compare the mean number of attempts with 1/p and the fraction needing more than three attempts with 0.3³.

P11. Recurrences against reality

Write a function that counts the work of merge sort by its recurrence (T(n) = T(⌊n/2⌋) + T(⌈n/2⌉) + n) and compare with n log₂ n for n = 1,024, 4,096 and 1,000,000. Then check that T(n) = T(n − 1) + n gives n(n + 1)/2 for n = 10,000.

Cumulative projects (chapters so far: 01–05)

C1. A collision-free order-code generator

Build a Java command-line tool that issues short, human-friendly order codes. Requirements: codes are 7 characters from an alphabet without look-alikes (no 0/O, 1/l/I); generated from a sequence number by a bijection (so collisions are impossible), but not obviously sequential to customers; a --decode mode turns a code back into the number; codes read from standard input are validated with a check character that catches every single-character typo and (almost) every swap of adjacent characters. Prove (in a short written argument) that your encoding is a bijection on its range, compute how many codes it supports, and test decode(encode(n)) = n for a million random n plus the boundary values.

Combines: arguments, stdin, exit codes (ch 01); integer arithmetic, overflow, bit manipulation, testing (ch 02); arrays and maps for the alphabet (ch 03); complexity (ch 04); bijections, modular arithmetic, counting, proof (ch 05).

C2. Feature-flag rules you can trust

Write a small rule engine (Java) for feature flags. Rules are Boolean expressions over user attributes (country == "IN" && appVersion >= 5 || inBeta), parsed from a text file given as an argument. Requirements: parse rules into an AST with a sealed interface and records; evaluate them; detect two rules that are equivalent or where one implies the other, by exhaustive evaluation over the finite set of attribute values that appear in the rules; report rules that are always true or always false (tautologies and contradictions) as warnings on stderr; exit 2 if any warnings. Explain why exhaustive checking works here and when it would stop working.

Combines: files, arguments, stderr, exit codes (ch 01); sealed types, records, recursion over an AST, error handling (ch 02); sets and maps (ch 03); recursive descent parsing, complexity (ch 04); propositional logic, normal forms, truth tables, implication (ch 05).

C3. Capacity and collision budget for a URL shortener

TiffinBox wants short links for SMS (Volume 23: every character costs). Write a design note plus a Python simulation that answers: how long must random codes be so that the probability of any collision over 5 years, at 2 million links per day, stays below one in a million, if the service checks for collisions on insert and retries? How many retries per insert should you expect near the end of the 5 years? Compare with sequence-based (bijective) codes, and with storing a hash of the URL. Include the probability arguments (birthday bound, geometric retries) and verify the retry estimate by simulation at a scaled-down size.

Combines: SMS encoding limits (Volume 23 via ch 01's encodings); integer types and overflow (ch 02); hash sets and database unique indexes (ch 03); expected complexity (ch 04); birthday bound, expectation, geometric distribution, counting (ch 05).

What the chapter leaves out

Tails, percentiles and fan-out

The chapter covers expectation and variance; production systems live in the tails. Latency distributions are skewed, so the mean hides the slow requests users notice: report p50, p99 and p99.9, and never average percentiles across servers (merge the distributions instead). Fan-out makes tails dominant: if one request calls 100 services in parallel and each is slow 1% of the time, the request is slow with probability 1 − 0.99¹⁰⁰ = 63% (computed; 10 services: 9.6%). This is "the tail at scale" (Dean and Barroso): mitigations include hedged requests (send a duplicate after the p95 delay), reducing fan-out, and timeouts with partial results.

Queueing: why systems fall off a cliff

A little queueing theory explains most performance surprises. In the simplest model (M/M/1: random arrivals, one server), the mean time in the system is the service time ÷ (1 − utilisation): 2× at 50% utilisation, 5× at 80%, 10× at 90%, 20× at 95% and 100× at 99% (computed). Real systems aren't exactly M/M/1, but the shape holds: latency explodes as utilisation approaches 100%, which is why you plan capacity for 60–70% at peak, why a small traffic increase can cause a large latency increase, and why load shedding and backpressure exist. Little's law (L = λW, Volume 24's chapter 07) connects queue length, throughput and waiting time.

Modular arithmetic and consistent hashing

Modular arithmetic appears briefly in the chapter; in systems it's everywhere: hash tables (index = hash mod capacity), sharding, check digits (C1), cyclic buffers, and cryptography. One important consequence: sharding by hash(key) mod N moves almost every key when N changes. Measured: going from 10 to 11 servers moved 90.7% of 100,000 keys, a cache-wide miss storm or a full data migration. Consistent hashing places servers and keys on a ring (with many virtual nodes per server) and moves only about 1/N of keys: measured 9.5% (ideal 9.1%). It's used by Cassandra, DynamoDB-style stores, CDNs and load balancers (Volume 5).

Randomness: statistical versus cryptographic

The chapter's probability assumes good randomness, but generators differ. java.util.Random and Python's random are fast pseudo-random generators: fine for simulations and shuffling test data, but their output can be predicted from a few observed values. Anything security-related (tokens, password-reset links, session IDs, OTPs, salts) must use a cryptographically secure generator (SecureRandom, Python's secrets). Seeds matter in the other direction: simulations and tests should use fixed seeds (logged) so results are reproducible (chapter 04's S5).

Statistics for decisions: experiments and significance

Engineers increasingly decide with data: A/B tests, canary analysis, performance comparisons. The chapter's probability foundations lead to a few practical rules: decide the metric and sample size before looking (peeking repeatedly inflates false positives); a difference smaller than the noise between two identical runs isn't a difference; use confidence intervals, not single numbers; beware the base rate (P6) and correlated samples (P7); and with many metrics, some will "improve" by chance (multiple comparisons). For benchmark comparisons, run each variant several times and compare distributions.

Formal methods, briefly

Beyond proofs on paper and executable invariants, some teams model designs formally: TLA+ (used at Amazon Web Services for distributed-system designs) and other model checkers explore every interleaving of a small model to find bugs that tests almost never hit, such as rare race conditions in replication protocols. SAT/SMT solvers (C2) check rule sets and configurations. You don't need these daily, but a senior engineer should recognise when a design (a distributed lock, a payment state machine) is subtle enough to deserve one.

Senior exercises

S1. The availability math of a design review

A design proposes: a load balancer (99.99%), three application instances in one availability zone (99.9% each), and one primary database (99.95%) with an asynchronous replica in another zone. The author claims "five nines with three app instances". Compute the actual availability under independence, explain what independence misses, identify the real weak points, and write the review comment with concrete changes.

S2. Is the new version really faster?

A colleague benchmarks a change: old version 412 ms, new version 398 ms (one run each) and claims a 3.4% improvement. Another run of the old version gives 431 ms. Using the chapter's probability and the gaps section, explain why the claim isn't supported, design a benchmark protocol that could support or refute it, and say how you'd present the result.

S3. Retry storms and the expected-value trap

A checkout service calls a payment gateway with up to 3 immediate retries. Normally 2% of calls fail (randomly). During a 2-minute gateway brownout, 80% fail. Compute the expected number of gateway calls per checkout in both situations, explain why retries make the brownout worse, and redesign the retry policy. Use T10's geometric reasoning and the queueing gap.

S4. Rebalancing a cache cluster without a meltdown

Your 10-node Redis cache shards keys with hash(key) % 10. Black Friday is next week and you need 15 nodes. The database behind the cache can absorb about 20% of the normal read traffic. Using the gaps section's measurements, explain what happens if you just change the modulus, compute roughly how many keys move, and design a migration plan (and a better long-term scheme).

S5. Secure tokens versus random-looking IDs

Code review finds three things: password-reset tokens generated with new Random().nextLong() (as a hex string); order IDs from UUID.randomUUID() exposed in URLs; and invitation codes as 6 random digits from SecureRandom, valid for 30 days without attempt limits. For each, explain the risk using this chapter's counting and probability (and the gaps section), and specify the fix.

S6. Explain the birthday paradox to a product manager

Product wants 5-character order codes "because 62⁵ is 916 million, we'll never run out". In under 150 words, explain why collisions start much sooner than "running out", with one concrete number from this chapter and one analogy, and propose two options with their trade-offs in product terms.