The ABRACADABRA Problem
A classic interview puzzle asking for the expected number of coin flips (or letter draws) until a specific target string first appears, solved elegantly with a martingale betting argument rather than brute-force recursion.
How many random letter draws, on average, until you've seen the sequence "ABRACADABRA" appear as a run? Working this out by tracking every possible partial match by hand is painful. The martingale trick reframes the problem as a fair casino game, and the answer falls out almost by inspection.
The trick
Imagine a new gambler arrives before every letter draw and bets $1 that the next letters spell out "ABRACADABRA" starting right now, at fair odds (so a correct guess on a -letter alphabet pays times the stake at each successive correct letter, and the gambler reinvests all winnings on the next letter). Every gambler's bet is a fair game, so the casino's expected profit is always zero regardless of when you stop. Stop at the first moment the target string has just appeared. The expected total money the casino has taken in equals the expected number of gamblers who have played, which is the expected stopping time — and the casino's winnings at that stopping instant can be computed directly from the overlaps in the target word with its own prefixes.
Worked example
For an 11-letter word over a 26-letter alphabet, the expected number of draws equals summed over every length- prefix of the word that is also a suffix of the word (including , the whole word). "ABRACADABRA" has two such self-overlaps: the whole word () and the prefix "A" which equals the suffix "A" (). The expected number of draws is — a huge number dominated by the term, with the small correction coming entirely from that one-letter self-overlap.
The expected waiting time for a target string to appear in random draws equals the sum of (alphabet size)^k over every prefix length at which the target overlaps with its own suffix — derived by modeling a sequence of fair $1 side-bets on the target appearing starting at each draw and using the fact that a fair game has zero expected profit at any stopping time.
Related concepts
Practice in interviews
Further reading
- Li, A Martingale Approach to the Study of Occurrence of Sequence Patterns