Music streaming app~30 min2s · 256 MBtarget O(top log log top + q) time, O(top) spacenumber-theory
You work on a music streaming app with a "mix" feature. A mix repeats in blocks of b slots, and a of the slots in each block play tracks from your library, where 1 ≤ a ≤ b. For the listener, the share a / b is what matters. A mix of 2 out of 4 slots sounds the same as 1 out of 2.
Your team lead asks: "For each size limit n, how many different shares can a mix have, if the block length is at most n?" A request holds up to 100,000 limits, each up to 500,000.
Write distinct_patterns(limits).
limits[i] is the largest block length n for query i.a / b with 1 ≤ a ≤ b ≤ n. Two shares are the same when the fractions are equal.For n = 1 the only share is 1 out of 1.
Input: limits = [1, 2, 5, 10]
Output: [1, 2, 10, 32]A share is new exactly when a and b have no common factor. The table lists those pairs for n = 5.
Block length b |
Values of a with no common factor |
Count |
|---|---|---|
| 1 | 1 | 1 |
| 2 | 1 | 1 |
| 3 | 1, 2 | 2 |
| 4 | 1, 3 | 2 |
| 5 | 1, 2, 3, 4 | 4 |
The total for n = 5 is 1 + 1 + 2 + 2 + 4 = 10.
Input: limits = [30]
Output: [278]Input: limits = [7, 1]
Output: [18, 1]For n = 7, the counts per block length are 1, 1, 2, 2, 4, 2 and 6, which add up to 18.
1 ≤ len(limits) ≤ 100,0001 ≤ limits[i] ≤ 500,000Testing every pair a ≤ b ≤ n for gcd one takes about n × n / 2 tests for a single limit, which is 125 billion for n = 500,000. The counts per block length can be computed for every length up to 500,000 in about 1,400,000 steps. After a running total, every query is one read.