Count numbers with same popcount up to all-ones bound
Company: SoFi
Role: Software Engineer
Category: Coding & Algorithms
Difficulty: easy
Interview Round: Take-home Project
Quick Answer: This question evaluates skill in bit manipulation and combinatorial counting over binary representations in the Coding & Algorithms domain, specifically reasoning about popcount and counting integers up to an all-ones bound.
Constraints
- `1 <= n <= 10^18`
- Target time complexity: `O(log n)`
- `n` fits in at most 60 bits
Examples
Input: (5,)
Expected Output: 2
Explanation: `5` is `101`, so `k = 3` and `f(n) = 7` (`111`). The numbers from `1` to `7` with exactly two set bits are `3`, `5`, and `6`. Excluding `5`, the answer is `2`.
Input: (7,)
Expected Output: 0
Explanation: `7` is `111`, so it already equals `f(n)`. The only number from `1` to `7` with three set bits is `7` itself, so excluding it leaves `0`.
Input: (1,)
Expected Output: 0
Explanation: `1` is `1`, so `f(n) = 1`. The only number in range is `1` itself, and it must be excluded.
Input: (8,)
Expected Output: 3
Explanation: `8` is `1000`, so `k = 4` and `f(n) = 15` (`1111`). The numbers with one set bit are `1`, `2`, `4`, and `8`. Excluding `8`, the answer is `3`.
Input: (10,)
Expected Output: 5
Explanation: `10` is `1010`, so `k = 4` and `popcount(n) = 2`. There are `C(4, 2) = 6` numbers from `0` to `15` with exactly two ones. Since `0` is not among them and `10` must be excluded, the answer is `6 - 1 = 5`.
Input: (13,)
Expected Output: 3
Explanation: `13` is `1101`, so `k = 4` and `popcount(n) = 3`. The numbers from `1` to `15` with three set bits are `7`, `11`, `13`, and `14`. Excluding `13`, the answer is `3`.
Input: (576460752303423488,)
Expected Output: 59
Explanation: This is `2^59`, which has bit-length `60` and popcount `1`. Among all numbers from `1` to `2^60 - 1`, there are exactly `60` powers of two, so excluding `n` leaves `59`.
Hints
- If `n` has bit-length `k`, then every number from `0` to `2^k - 1` can be viewed as a binary string of length `k` by allowing leading zeros.
- How many length-`k` binary strings contain exactly `popcount(n)` ones?