Music streaming app~30 min2s · 256 MBtarget O(n) time, O(n) spaceclassic twin: lc-264k-way-merge · heaps
A music app shows a live equaliser. It runs a Fourier transform on blocks of audio samples, and the transform runs fast only when the block length has no prime factor larger than 5. Lengths made only from the factors 2, 3 and 5 are allowed, and so is 1.
The team numbers the allowed lengths in increasing order: 1, 2, 3, 4, 5, 6, 8, 9, 10, 12, and so on. The numbers 7, 11 and 13 are not allowed. Your job is to find the n-th allowed length.
Write nth_allowed(n).
n-th one. The result always fits in an int.Input: n = 10
Output: 12Every allowed length after 1 is 2, 3 or 5 times an earlier allowed length. So there are three sorted lists to merge: the list times 2, the list times 3 and the list times 5. Each has a pointer into the answer list, and a heap holds each list's next candidate.
| Popped | Added to the list? | Candidates in the heap after the step | The list so far |
|---|---|---|---|
| 2 (from 2 x 1) | yes | 3, 4, 5 | 1, 2 |
| 3 (from 3 x 1) | yes | 4, 5, 6 | 1, 2, 3 |
| 4 (from 2 x 2) | yes | 5, 6, 6 | 1, 2, 3, 4 |
| 5 (from 5 x 1) | yes | 6, 6, 10 | 1, 2, 3, 4, 5 |
| 6 (from 2 x 3) | yes | 6, 8, 10 | 1, 2, 3, 4, 5, 6 |
| 6 (from 3 x 2) | no: a repeat | 8, 9, 10 | 1, 2, 3, 4, 5, 6 |
| 8 (from 2 x 4) | yes | 9, 10, 10 | 1, 2, 3, 4, 5, 6, 8 |
| 9 (from 3 x 3) | yes | 10, 10, 12 | 1, 2, 3, 4, 5, 6, 8, 9 |
| 10 (from 2 x 5) | yes | 10, 12, 12 | 1, 2, 3, 4, 5, 6, 8, 9, 10 |
| 10 (from 5 x 2) | no: a repeat | 12, 12, 15 | 1, 2, 3, 4, 5, 6, 8, 9, 10 |
| 12 (from 2 x 6) | yes | 1, 2, 3, 4, 5, 6, 8, 9, 10, 12 |
The list has 10 values, and the 10th is 12.
Input: n = 1
Output: 1The first allowed length is 1.
Input: n = 7
Output: 8The allowed lengths are 1, 2, 3, 4, 5, 6, 8. Seven is not allowed, so the 7th length is 8.
1 ≤ n ≤ 1690The 1690th allowed length is 2,123,366,400, which is close to the largest int. Testing every number up to it, one by one, takes about 2 × 10^9 tests, each with a few divisions. That is far too slow.
Only 1,690 lengths are wanted, so build them, in order, from each other.