Music streaming app~25 min2s · 256 MBtarget O(log n) time, O(log² n) spaceclassic twin: lc-338bit-manipulation
A streaming service numbers its live sessions from 0 to n. The routing layer sends a session to lane k when its number has exactly k bits set to 1 in binary.
The capacity team wants to size each lane before the numbers are used. Your team lead asks: "How many session numbers from 0 to n go to lane k?"
Write sessions_in_lane(n, k).
n is the last session number. The numbers are 0, 1, ..., n, and n is included.k is the lane. A number is in the lane when its binary form has exactly k bits equal to 1.n are in lane k.Input: n = 20, k = 2
Output: 9The numbers from 0 to 20 with exactly two 1 bits are 3, 5, 6, 9, 10, 12, 17, 18 and 20. The code walks the bits of 20, which is 10100, from the top. At each 1 bit it counts the numbers that put a 0 there and anything below.
| Bit b | Bit of 20 | Ones still needed | Numbers added | Ones in prefix | Total |
|---|---|---|---|---|---|
| 4 | 1 | 2 | 6 | 1 | 6 |
| 3 | 0 | - | 0 | 1 | 6 |
| 2 | 1 | 1 | 2 | 2 | 8 |
| 1 | 0 | - | 0 | 2 | 8 |
| 0 | 0 | - | 0 | 2 | 8 |
The loop ends with 2 ones in the prefix, which equals k, so n itself adds 1 more.
Input: n = 0, k = 0
Output: 1Only the number 0 has no 1 bit, so lane 0 holds one number.
Input: n = 7, k = 5
Output: 0The numbers up to 7 have at most 3 bits, so none has five 1 bits.
0 ≤ n ≤ 100,000,000,0000 ≤ k ≤ 40Testing every number from 0 to n costs up to 10^11 steps, far too slow even with one test for each number. A number of 37 bits has at most 37 positions, and a table of binomial coefficients tells how many ways the lower positions can hold the needed ones. The walk over the bits of n takes about 40 steps.