68 problems in nine parts: sketching, proof, algorithms, and games and invariants, ending with interview-length problems. Each has a hint and a full answer.
For CUMSA applicants. Please don't share outside the programme. Your progress is saved in this browser only.
Out loud. Talk through every question as if someone is listening; even better, have a friend read the question to you and give hints. Explaining while you think is the hardest part of the real interview, and it only improves with practice.
Timed. Give yourself about 15 minutes per question. If you are stuck after 5 minutes, open the hint; that is what an interviewer would do.
Small cases first. Almost every question here gets easier if you try n = 1, 2, 3 and look for a pattern. Then ask why the pattern holds; a pattern from three cases is not a proof.
Check the answer only at the end, and then ask: what was the key idea, and where else could I use it?
Part 1 · Questions 1–8
Graph sketching
For each graph, mark where it crosses the axes, turning points, asymptotes, symmetry, and what happens as x goes to ±infinity and near any awkward points. No calculator.
What does x ln x do as x tends to 0? (Compare how fast x goes to 0 with how fast ln x goes to minus infinity.)
Answer
Both tend to 0 as x tends to 0 (from below), are 0 at x = 1, and grow without limit. x ln x has a minimum at x = 1/e (value -1/e) and arrives at the origin with a vertical tangent. x2 ln x has its minimum at x = e-1/2 (value -1/(2e)) and arrives at the origin flat.
An oscillation trapped between ±e-x: it grows huge to the left and dies away to the right. Zeros at every multiple of π. It touches the envelopes where sin x = ±1, but its turning points are where tan x = 1, a little earlier (at π/4 + kπ).
It is even. Where is the denominator 0, and what is y for very large x?
Answer
Vertical asymptotes x = ±2, horizontal asymptote y = 1. Zeros at x = ±1; y(0) = 1/4, a local maximum. Between -2 and 2 it is a hump going down to minus infinity at both asymptotes, crossing zero at ±1. Outside, it comes down from plus infinity towards 1 from above (y = 1 + 3/(x2 - 4)).
Where are the zeros? How far apart are they for large x?
Answer
Even, between -1 and 1, flat at the origin (behaves like x2). Zeros at x = √(kπ); the gap between them shrinks like 1/x, so it oscillates faster and faster.
y = |x| + |x - 1| + |x - 2|. Where is it smallest? What if there are five points instead of three?
Hint
It is made of straight pieces. What is the gradient between 1 and 2?
Answer
Straight pieces with gradient -3, -1, 1, 3, so the minimum is at x = 1 (the middle point), with value 2. In general the sum of distances to some points is smallest at their median. This is why the best place for a shop on a straight road is at the middle customer, not at the average position.
Look at x very large, very negative, and 0. Is there a symmetry?
Answer
An S-shape from 0 to 1 through (0, 1/2), symmetric about that point (y(-x) = 1 - y(x)). The gradient is y(1 - y): a bell shape, largest (1/4) at x = 0. This "sigmoid" is used in neural networks.
What happens just to the left and just to the right of 0?
Answer
Tends to π/2 as x tends to 0 from the right and -π/2 from the left: a jump of π. Tends to 0 as x tends to ±infinity. Decreasing on each side. For x > 0 it equals π/2 - arctan x.
Swap x and y; replace (x, y) with (-x, -y). Try the lines y = x and y = -x.
Answer
An ellipse tilted at 45°. On y = -x: x2 = 1, so it reaches (1, -1), its furthest points from the origin. On y = x: 3x2 = 1, closest points (1/√3, 1/√3). It crosses the axes at (±1, 0) and (0, ±1).
n straight lines are drawn in the plane, no two parallel and no three through one point. Into how many regions do they cut the plane?
Hint
When you add the n-th line, how many old lines does it cross, and how many regions does it split?
Answer
The n-th line crosses n - 1 lines, so it passes through n regions and splits each in two, adding n. Total 1 + (1 + 2 + ... + n) = n(n + 1)/2 + 1: 2, 4, 7, 11, ...
Five points are placed inside a 1 × 1 square. Prove that two of them are within √2/2 of each other.
Hint
Cut the square into 4 pieces.
Answer
Cut it into four ½ × ½ squares. Two of the five points share a small square (the pigeonhole principle), and the longest distance in a small square is its diagonal, √2/2.
How many shortest routes are there along grid lines from (0, 0) to (m, n)? How many from (0, 0) to (n, n) never go above the diagonal y = x?
Hint
For the second part, count the bad routes: reflect the part of a bad route after it first touches the line y = x + 1.
Answer
A route is m right-steps and n up-steps in some order: C(m + n, n). A bad route first touches y = x + 1 at some point; reflecting the rest of it in that line turns it into a route to (n - 1, n + 1), and this works both ways. So good routes = C(2n, n) - C(2n, n - 1) = C(2n, n)/(n + 1), the Catalan numbers 1, 2, 5, 14, 42. They also count balanced bracket strings.
Prove that n5 - n is divisible by 30 for every whole number n.
Hint
30 = 2 × 3 × 5. Factorise n5 - n.
Answer
n5 - n = (n - 1)n(n + 1)(n2 + 1). The three consecutive numbers give factors 2 and 3. For 5: if n leaves remainder 0, 1 or 4 mod 5, one of n, n - 1, n + 1 is a multiple of 5; if 2 or 3, then n2 + 1 is (4 + 1 or 9 + 1).
In a tournament, every pair of players plays once and there are no draws. Prove you can list all the players so that each beat the next one in the list.
Hint
Induction: take a list for all but one player. Where can the last player be slotted in?
Answer
Given a list p1, ..., pk and a new player x: if x beat p1, put x first. Otherwise p1 beat x. Go along until the first pi that x beat and slot x in just before it; if there is none, put x last. This is exactly insertion sort. With binary search you can find a suitable gap quickly: any place where the player before beat x and x beat the player after.
Show that every amount of 8p or more can be paid exactly with 3p and 5p coins. Which amounts can't be paid?
Hint
Do 8, 9, 10 by hand. How do you get from n to n + 3?
Answer
8 = 3 + 5, 9 = 3 + 3 + 3, 10 = 5 + 5, and adding a 3p coin covers everything after. The impossible amounts are 1, 2, 4 and 7. For coins a and b with no common factor, the largest impossible amount is ab - a - b.
A stick is broken at two random points. What is the probability that the three pieces can form a triangle?
Hint
When can three lengths that add up to 1 make a triangle? Draw the two break points as a point in a square.
Answer
1/4. The pieces make a triangle exactly when each is shorter than 1/2. In the unit square of (first break, second break), that region is 1/4 of the area.
Part 3 · Questions 19–27
Algorithms
No programming needed: describe the method in words, say why it works, and say how many steps it takes.
How would you compute 31000 using far fewer than 999 multiplications? Is your method always the best? Try x15.
Hint
x2, x4, x8, ... Write 1000 in binary.
Answer
Square repeatedly and multiply together the powers matching the 1s in the binary form of n: at most about 2 log2 n multiplications (14 for 1000). It is not always the best. For x15 the binary method uses 6 multiplications, but x, x2, x3, x6, x12, x15 uses 5.
You have a 3-litre jug, a 5-litre jug and a tap. How do you measure exactly 4 litres? Which amounts can you measure with jugs of a and b litres?
Hint
Keep filling the 3 and pouring into the 5, emptying the 5 when it is full.
Answer
Fill 5, pour into 3 (leaves 2 in the 5), empty the 3, pour the 2 in, fill 5, top up the 3 (leaves 4 in the 5). Six steps. In general you can measure exactly the multiples of gcd(a, b), up to the size of the larger jug. This links to Euclid's algorithm: gcd(a, b) = gcd(b, a mod b).
A sorted list has been "rotated", for example 15, 18, 22, 2, 3, 6, 12. Find where the smallest number is by looking at only about log2 n entries.
Hint
Compare the middle entry with the last entry.
Answer
If the middle entry is bigger than the last, the drop (and the smallest number) is to the right of the middle; otherwise it is at the middle or to the left. Halve and repeat, as in binary search.
A sorted list of numbers and a target T. Find two numbers in the list that add up to T, in a single pass.
Hint
Start with one finger at each end.
Answer
If the two numbers under your fingers add up to more than T, move the right finger left; if less, move the left finger right. Why no pair is missed: when you move the right finger, its number is too big even with the smallest remaining partner, so it cannot be in any solution. n steps instead of n2/2 pairs.
Decide whether a string of brackets like (()(())) is balanced. Then allow three kinds of bracket: ( [ {. What do you need now?
Hint
For one kind of bracket, a single counter is enough. What goes wrong with three counters and ( [ ) ]?
Answer
One kind: count up for "(" and down for ")". The string is balanced if the count never goes negative and ends at 0. Several kinds: counters accept ( [ ) ], which is wrong. Use a stack: push each opening bracket, and each closing bracket must match the one on top, which you then pop. The string is balanced if every closing bracket matches and the stack ends empty.
You know a share's price for each of the next n days, e.g. 7, 1, 5, 3, 6, 4, 2, 8, 3. You may buy once and then sell once later. What is the most profit, and how do you find it in one pass?
Hint
If you sell on day j, which day should you have bought on?
Answer
Keep the lowest price so far. Each day, check today's price minus that lowest price. Here 8 - 1 = 7. Checking every buy/sell pair takes about n2/2 steps; this takes n.
When can you draw a figure (a set of dots and lines) without lifting your pen and without going over any line twice?
Hint
Count the lines meeting at each dot. What happens at a dot you pass through?
Answer
Each time you pass through a dot you use two of its lines. So all dots must have an even number of lines, except possibly the start and the end. The figure must be connected and have 0 or 2 "odd" dots; this is also enough (Euler). With 0 you finish where you started.
What is the fewest knight moves from one corner of a chessboard to the opposite corner? How would a computer find the fewest moves between any two squares?
Hint
Each knight move changes x + y by at most 3. Also, what colour square does a knight move to?
Answer
6. Lower bound: x + y must rise from 0 to 14 and each move adds at most 3, so at least 5 moves; but each move changes square colour, and the corners are the same colour, so the number of moves is even: at least 6. A computer uses breadth-first search: find every square 1 move away, then every new square 2 moves away, and so on.
There are 21 counters. Players take turns removing 1, 2 or 3; whoever takes the last counter wins. Should you go first? What if whoever takes the last counter loses?
Hint
Work backwards from 0, 1, 2, 3, 4, 5 counters.
Answer
Multiples of 4 are losing for the player to move: whatever they take, the opponent takes the rest of 4. 21 is not a multiple of 4, so go first and take 1, then always make the total taken in each round 4. If taking the last loses, the losing positions are 1, 5, 9, ..., 21. So go second.
Three piles of 3, 4 and 5 counters. A move takes any number of counters from one pile; whoever takes the last counter wins. Find a winning first move.
Hint
Write the piles in binary: 011, 100, 101. Try to leave an even number of 1s in every column.
Answer
Take 2 from the pile of 3, leaving 1, 4, 5 (001, 100, 101): every binary column has an even number of 1s (the XOR is 0). Any move breaks this, and you can always restore it. This is Nim.
Design a machine with a fixed number of states that reads a string of 0s and 1s, one at a time, and says at the end whether "101" appeared somewhere in it.
Hint
The states should record how much of "101" you have just seen: nothing, "1", "10", or all of it.
Answer
Four states. S0 (nothing useful): reading 1 goes to S1, 0 stays. S1 (ends in 1): 0 goes to S2, 1 stays in S1. S2 (ends in 10): 1 goes to S3, 0 goes back to S0. S3 (seen 101): stay forever. Accept in S3. The tricky step is S1 on reading 1: you should stay in S1, not go back to the start.
The numbers 1 to 10 are written on a board. Repeatedly rub out two numbers a and b and write |a - b|. Can the last number be 0? Now write a + b + ab instead. What is the last number?
Hint
For the first part, think about odd and even. For the second, add 1 to everything: what is (a + 1)(b + 1)?
Answer
|a - b| has the same parity as a + b, so the total stays odd (it starts at 55). The last number is odd, never 0. For the second, a + b + ab = (a + 1)(b + 1) - 1, so the product of (number + 1) never changes. The last number is 2 × 3 × ... × 11 - 1 = 11! - 1 = 39,916,799, whatever order you choose.
In a group, some pairs are friends. Show you can split everyone into two rooms so that each person has at most half of their friends in their own room.
Hint
Start with any split. If someone is unhappy, move them. Why does this stop?
Answer
Count the pairs of friends in the same room. Moving an unhappy person (more than half their friends in their room) to the other room lowers this count by at least 1. The count can't go below 0, so the moving must stop, and then everyone is happy. This "improve until stuck" method is called local search.
List all eight 3-bit strings (000 to 111) so that neighbours in the list differ in exactly one bit. Can you do it for n bits?
Hint
Take a list for 2 bits, write it forwards and then backwards, and add an extra bit to tell the halves apart.
Answer
000, 001, 011, 010, 110, 111, 101, 100. For n bits: write the (n - 1)-bit list with a 0 in front, then the same list backwards with a 1 in front. Where the halves meet, only the front bit changes. This is the Gray code, used in rotary sensors so that a reading taken mid-change is never far wrong.
100 lockers are closed. Person 1 opens every locker. Person 2 changes every 2nd locker (closing it if open, opening it if closed), person 3 every 3rd, and so on up to person 100. Which lockers end up open?
Hint
Locker n is changed once for each number that divides n.
Answer
Divisors come in pairs (d and n/d) except when n is a perfect square. So squares have an odd number of divisors and end open: 1, 4, 9, ..., 100, ten lockers.
Round 2
More of the same, slightly harder on average. Part 9 contains longer, multi-part problems that run like a real interview question: try to do each one in 20 minutes, out loud.
Is it odd or even? What is it like for small x and for large x?
Answer
Odd. Like y = x near 0 and like 1/x for large x, so it tends to 0 at both ends. Maximum 1/2 at x = 1 and minimum -1/2 at x = -1 (by calculus, or from 1 + x2 ≥ 2x).
Treat x tending to 0 from the right and from the left separately.
Answer
As x tends to 0 from the right, 1/x tends to infinity and y tends to infinity. From the left, 1/x tends to minus infinity and y tends to 0, so the curve heads into the origin, which is missing. y tends to 1 as x tends to ±infinity: above 1 on the right, below 1 on the left. Always positive and decreasing on each side.
|sin x| is at most 1. What is ln of something at most 1?
Answer
y ≤ 0 everywhere, with maxima of 0 at x = π/2 + kπ and vertical asymptotes (y tends to minus infinity) at every multiple of π. Repeating arches with period π.
Which x are allowed? Sketch y = x√(1 - x2) and reflect it.
Answer
Only |x| ≤ 1. y = ±x√(1 - x2): a figure-of-eight through (-1, 0), (0, 0) and (1, 0), crossing itself at the origin along the lines y = ±x. Widest at x = ±1/√2, where |y| = 1/2.
In how many ways can n identical sweets be shared among k children (some may get none)?
Hint
Write the sweets as stars in a row and use k - 1 bars to divide them.
Answer
Any arrangement of n stars and k - 1 bars gives a sharing, and the other way round: C(n + k - 1, k - 1). For example, 5 sweets among 3 children: C(7, 2) = 21.
n letters are put into their n addressed envelopes at random. (a) For n = 4, in how many ways is every letter in the wrong envelope? (b) On average, how many letters are in the right envelope?
Hint
(b) Don't find the whole distribution. What is the chance that letter 1 is right?
Answer
(a) 9 (of 24). (b) Each letter is right with probability 1/n, and there are n letters, so on average exactly 1, whatever n is (linearity of expectation). Bonus: the chance that every letter is wrong tends to 1/e ≈ 0.37.
How many people do you need in a room before the chance that two share a birthday is more than 1/2?
Hint
Work out the chance that all birthdays are different, one person at a time.
Answer
23. P(all different) = (365/365)(364/365)(363/365)..., which drops below 1/2 at the 23rd person. It is surprisingly small because 23 people make 253 pairs. In CS this is why random "fingerprints" (hashes) of n bits start clashing after about 2n/2 items.
Induction: what do you add to (1 + ... + n)2 to get (1 + ... + n + (n + 1))2?
Answer
Write T = n(n + 1)/2. Then (T + n + 1)2 - T2 = 2T(n + 1) + (n + 1)2 = n(n + 1)2 + (n + 1)2 = (n + 1)3, which is exactly the next cube. Picture version: an L-shaped strip of width n + 1 around a T × T square has area (n + 1)3.
Prove there are infinitely many primes. Then prove there are infinitely many primes that leave remainder 3 when divided by 4.
Hint
Second part: if p1, ..., pk were all of them, look at 4p1p2...pk - 1. What happens when you multiply numbers that are all 1 mod 4?
Answer
N = 4p1...pk - 1 is 3 mod 4 and odd. A product of numbers that are all 1 mod 4 is 1 mod 4, so N has a prime factor that is 3 mod 4. It cannot be any pi (N leaves remainder -1 when divided by pi), so it is a new one.
Choose any n + 1 numbers from 1, 2, ..., 2n. Prove that one of them divides another. Can you choose n numbers with no such pair?
Hint
Write each number as a power of 2 times an odd number. How many possible odd parts are there?
Answer
Each number is 2a × (odd number), and there are only n odd numbers below 2n. With n + 1 numbers, two have the same odd part (pigeonhole), and the one with the smaller power of 2 divides the other. With n numbers it can fail: take n + 1, n + 2, ..., 2n.
Nine coins look identical, but one is heavier. Find it with two uses of a balance. How many coins could you handle with k weighings?
Hint
A weighing has three possible results, not two.
Answer
Weigh 3 against 3. If they balance, the heavy coin is in the other 3; otherwise it is in the heavier group. Then weigh 1 against 1 from that group in the same way. Each weighing divides the possibilities by 3, so k weighings handle 3k coins, and no method can do more (k weighings have only 3k possible outcomes).
How many comparisons does it take to merge two sorted lists of n numbers each into one sorted list? Use this to sort a list by splitting it in half (merge sort). Roughly how many comparisons does it use?
Hint
Merging: compare the two front items, take the smaller. For merge sort, how many levels of halving are there, and how much merging happens at each level?
Answer
Merging takes at most 2n - 1 comparisons, because each comparison places one item. Merge sort has about log2 n levels, each doing about n comparisons of merging: about n log2 n in total, against about n2/2 for simple methods. For a million items that is about 20 million against 500 billion.
To list the primes up to n, you write out 2 to n and cross out the multiples of each prime in turn (the Sieve of Eratosthenes). Why can you stop once you reach √n?
Hint
If a number up to n is not prime, how big can its smallest prime factor be?
Answer
A composite m = ab with a ≤ b has a ≤ √m ≤ √n. So every composite up to n has a prime factor at most √n and has already been crossed out.
Sort a million exam scores, each a whole number from 0 to 100. Can you do it faster than a general sorting method?
Hint
You don't need to compare scores with each other at all.
Answer
Count how many students got each score (101 counters, one pass), then write out the scores in order using the counts. That is about n + 101 steps. The n log n limit only applies to methods that work by comparing items; here we use the fact that there are only 101 possible values (counting sort).
A row of red, white and blue balls. Rearrange them so all the reds come first, then whites, then blues, in one pass, using only swaps.
Hint
Keep three regions: done-red at the front, done-blue at the back, and unknown in between.
Answer
Keep three markers: the end of the red region, the current position, and the start of the blue region. Look at the current ball. Red: swap it to the end of the red region and move both markers on. White: just move on. Blue: swap it to just before the blue region, shrink that region, and look at the ball you swapped in (don't move on). Each step shrinks the unknown region, so it takes n steps.
Coins are worth 1, 3 and 4. "Always take the biggest coin that fits" pays 6 as 4 + 1 + 1. Is that the fewest coins? Describe a method that always finds the fewest.
Hint
Let best(n) be the fewest coins that make n. What could the last coin be?
Answer
No: 3 + 3 uses 2. best(0) = 0 and best(n) = 1 + the smallest of best(n - c) over the coin values c ≤ n. Work it out for n = 1, 2, 3, ... in order, so each step reuses earlier answers (dynamic programming). This takes about n × (number of coin types) steps.
A conference has many talks, each with a start and end time, and you want to attend as many talks as possible in full. Which talk should you pick first? Prove it.
Hint
Try "shortest first" and "earliest start first" on small examples. One rule works; find the counter-examples for the others.
Answer
Pick the talk that ends earliest, then repeat with the talks that start after it. Shortest-first fails (a short talk overlapping two long ones that don't overlap each other), and so does earliest-start (one long talk covering everything). Proof: take any best schedule. Its first talk ends no earlier than yours, so swap it for yours; nothing else clashes. Repeat for the rest.
What does n AND (n - 1) do to the binary digits of n? Use it to test whether n is a power of 2, and to count the 1s in n.
Hint
Try n = 12 (1100) and n - 1 = 11 (1011).
Answer
Subtracting 1 flips the lowest 1 bit and every 0 below it, so the AND removes the lowest 1 bit (1100 becomes 1000). n > 0 is a power of 2 exactly when n AND (n - 1) = 0. To count the 1s, repeat until you reach 0; the number of steps is the number of 1s.
Swap the values of two variables x and y without using a third variable.
Hint
XOR (written ⊕) has the property a ⊕ a = 0. Or use addition and subtraction.
Answer
x = x ⊕ y; y = x ⊕ y; x = x ⊕ y. After the second line, y = (x ⊕ y) ⊕ y = x; after the third, x = (x ⊕ y) ⊕ x = y. The version with x = x + y, y = x - y, x = x - y also works but can overflow. Follow-up: what goes wrong if x and y are the same memory location? (Both become 0.)
A list has 100 statements. Statement k says: "Exactly k of the statements in this list are false." Which statements are true?
Hint
Can two of them be true at the same time?
Answer
They contradict each other, so at most one is true. If none were true, all 100 would be false, which makes statement 100 true: a contradiction. So exactly one is true and 99 are false: statement 99 is the true one.
Colour the square in row i, column j with colour (i + j) mod 4. How many of each colour does one tile cover?
Answer
No. Every tile, flat or upright, covers one square of each of the four colours, so a covering needs 25 squares of each. But the board has 26, 25, 25 and 24. (A computer search confirms no covering exists.)
You may flip all the colours in any whole row or whole column of a chessboard. Starting from the normal chessboard, can you reach a board with exactly one black square?
Hint
Look at any 2 × 2 block. What does a flip do to the number of black squares in it?
Answer
No. A row or column flip changes either 0 or 2 squares of any 2 × 2 block, so the number of black squares in each block stays even or stays odd. On a chessboard every block has 2 (even). A board with exactly one black square has a block containing it with 1 (odd).
Two players take turns placing identical coins flat on a round table without overlapping. Whoever cannot place a coin loses. Who wins?
Hint
The first player's first coin goes somewhere special.
Answer
The first player. Place the first coin exactly in the centre; then, whenever the opponent places a coin, place one in the mirror-image position through the centre. By symmetry that spot is always free, so the first player always has a move.
Start with a whole number n ≥ 2. A move replaces the number with (number - d), where d is any divisor of the number smaller than the number itself. Whoever is left facing 1 (no move possible) loses. For which n does the first player win?
Hint
Work out n = 1 to 8. What do odd numbers' divisors look like?
Answer
The first player wins exactly when n is even (checked by computer up to 20; the argument works for all n). From an even number, subtract 1 to give an odd number. From an odd number, every divisor is odd, so the result is even. So the player facing an odd number always hands back an even one, and eventually faces 1.
A robot starts at the origin facing north and repeats a command string forever: F moves forward 1, L turns left 90°, R turns right 90°. When does it stay within a bounded area?
Hint
Run the string once. What matters is where it ends up and which way it faces.
Answer
Exactly when, after one run of the string, it is back at the origin or facing a different direction. If it faces a different direction, then after at most 4 runs its displacements cancel out and it is back at the start (checked on random strings). If it is facing north but not at the origin, every run moves it the same amount further away.
Show that among any 6 people there are 3 who all know each other or 3 who are all strangers to each other. Is 5 people enough?
Hint
Pick one person. Of the other 5, at least 3 are all friends or all strangers with them.
Answer
Person A has at least 3 friends or at least 3 strangers among the other 5; say 3 friends, B, C and D. If any two of B, C, D know each other, those two and A make a triangle of friends. If not, B, C, D are three strangers. 5 is not enough: put 5 people in a circle, with each person knowing only their two neighbours.
(a) On average, how many coin tosses until you see two heads in a row (HH)? (b) Until you see heads then tails (HT)? (c) Why are the answers different, when HH and HT are equally likely in any two given tosses?
Hint
Make a machine with a state for each amount of progress, like Question 31. Let Es be the expected number of tosses still needed from state s.
Answer
(a) 6. From the start, E0 = 1 + (EH + E0)/2 and EH = 1 + (0 + E0)/2, which give E0 = 6. (b) 4: once you have an H, you just wait for a T (2 more on average), and a further H doesn't undo your progress. (c) In HH, a failure (a T) throws away all progress; in HT, a failure (another H) keeps it. Copies of HH can overlap (HHH contains two), so they come in clumps with longer gaps in between. Extension: for a die, two 6s in a row takes 42 rolls on average, but a 6 followed by a 5 takes only 36 (checked by simulation).
(a) Show that 4 numbers can always be sorted with 5 comparisons. (b) Prove that 4 comparisons are not enough. (c) What does the same argument say about 5 numbers?
Hint
(b) How many possible orders are there? How many different outcomes can 4 yes/no comparisons have?
Answer
(a) Compare a with b and c with d, then the two winners and the two losers. That leaves the two middle numbers, which need one more comparison: 5. (b) There are 24 possible orders, but 4 comparisons have only 24 = 16 possible answer patterns, so two different orders would give the same answers and could not be told apart. (c) 120 orders > 26 = 64, so at least 7 comparisons. 7 is in fact possible, but it is hard to find. In general, sorting needs at least log2(n!) ≈ n log2 n comparisons, so merge sort (Question 49) is about as good as possible.
A lift serves floors 1 to 10. People press buttons for the floors they want, and new requests can arrive at any time. (a) "Always go to the nearest requested floor": what can go wrong? (b) Suggest a better rule and argue that nobody waits forever. (c) What would you measure to compare two rules?
Hint
(a) Imagine a steady stream of requests on floors 1 and 2 while someone waits on floor 10.
Answer
This one is open-ended, like many real interview questions. (a) Starvation: requests near the lift keep winning, and the person on floor 10 may never be served. (b) The "lift algorithm" (also used by disk drives, as SCAN): keep going in one direction while there are requests ahead, then reverse. In each direction the lift reaches every requested floor within one sweep, so the longest wait is at most about two full trips of the building. (c) Average waiting time, worst waiting time, and energy (distance travelled). The rules trade these off against each other: nearest-first is good on average but terrible in the worst case.
You are given the coordinates of n towns. (a) How would you find the two closest towns? How long does that take? (b) If all the towns are on a straight road, can you do better? (c) In the plane, the closest pair can be found in about n log n steps. Can you see how?
Hint
(b) Sort first. (c) Split the towns into a left half and a right half by x-coordinate. The closest pair is either inside one half or crosses the dividing line.
Answer
(a) Check every pair: n(n - 1)/2 distances. (b) Sort the positions; the closest pair must be next to each other in sorted order. That is about n log n for the sort plus n checks. (c) Solve each half recursively and let d be the smaller answer. A crossing pair closer than d must lie within d of the dividing line. Sort that strip by y: each town only needs comparing with the few towns just above it, at most about 7, because more than that would pack too many towns, all at least d apart, into a d × 2d box. So the extra work per level is about n, and there are about log n levels.
A secret number between 1 and 1000 must be found with yes/no questions. (a) What is the fewest number of questions that always works? (b) Now you must write down all your questions in advance, before hearing any answers. How many do you need? (c) Now the person answering may lie once. Explain why 10 questions can't be enough, and roughly how many you would need.
Hint
(c) With one possible lie, the "situation" is (number, which answer was the lie, or no lie). Count those situations, and count the possible answer patterns.
Answer
(a) 10, since 210 = 1024 ≥ 1000 > 29. Halve each time. (b) Still 10: ask "is the k-th binary digit of your number 1?" for k = 1 to 10. The answers spell out the number. (c) With q questions, each number can come with no lie or a lie on any one of the q answers: q + 1 situations per number. These all need different answer patterns (otherwise you could not tell which number it was), so 1000(q + 1) ≤ 2q. This fails for q = 10 and first holds at q = 14 (1000 × 15 = 15,000 ≤ 16,384). The same counting is behind error-correcting codes: a message survives one flipped bit only if the extra check bits cover every possible flip.
Where to find more
Oxford MAT past papers, especially Questions 6 and 7 from 2007 to 2014 (maths.ox.ac.uk). These are the closest written questions to CS interview problems; solutions are online.
TMUA and STEP past papers for proof and sketching practice.
British Informatics Olympiad Round 1 papers from 2000 to 2012 (olympiad.org.uk): do the written parts by hand.
Books: Levitin and Levitin, Algorithmic Puzzles; Zeitz, The Art and Craft of Problem Solving; Mason, Burton and Stacey, Thinking Mathematically.
The Oxford Computer Science sample interview problems page (cs.ox.ac.uk), and the University of Cambridge's own videos of example interviews.