Social feed~30 min2s · 256 MBtarget O(n²) time, O(n²) spacedp
A social feed lets replies nest. A thread opens with ( and closes with ). A layout is a text of pairs opening and pairs closing brackets that never closes a thread that is not open.
The feed limits how deep threads may nest. The design team wants to know how many layouts exist, but not the layouts themselves.
Your team lead says: Count the valid layouts for n threads and a depth limit d. The count can be huge.
Write count_thread_layouts(pairs, max_depth).
pairs opening brackets ( and pairs closing brackets ).) than (, and the whole text has equal numbers of both.( that are open at one moment. A counted text has depth at most max_depth.Input: pairs = 3, max_depth = 3
Output: 5A search that lists the texts reaches the same pair of counts again and again. Here the pair is the number of brackets opened and the number closed. A cache keyed by that pair counts each pair once.
| Call | Opened, closed | What happens |
|---|---|---|
| 1 | 0, 0 | not stored: opens a bracket |
| 2 | 1, 0 | not stored: opens a bracket |
| 3 | 2, 0 | not stored: opens a bracket |
| 4 | 3, 0 | not stored: only a close is left |
| 5 | 3, 1 | not stored: closes |
| 6 | 3, 2 | not stored: closes |
| 7 | 3, 3 | every bracket is placed: 1 text |
| 8 | 2, 1 | not stored: opens, then closes |
| 9 | 3, 1 | stored: returns 1 at once |
| 10 | 2, 2 | not stored: opens |
| 11 | 3, 2 | stored: returns 1 at once |
| 12 | 1, 1 | not stored: opens |
| 13 | 2, 1 | stored: returns 2 at once |
The cached count makes 13 calls, where the plain search makes 22. There are 5 valid texts.
Input: pairs = 3, max_depth = 2
Output: 4A depth limit of 2 removes the text with depth 3. There are 4 valid texts left.
Input: pairs = 4, max_depth = 1
Output: 1With a depth limit of 1, every pair must close before the next one opens. There is 1 text.
1 ≤ pairs ≤ 301 ≤ max_depth ≤ 30For 30 pairs and no limit, the answer is 3,814,986,502,092,304, the 30th Catalan number. It is below 2^53, so it is exact in every language, but it is far too large to list. A search that lists the texts makes about five calls for each text. The cached count makes 931 calls and stores 495 counts.