Quant Memo
Coding/●●●●●

Count set bits for every number up to n

For every integer i from 0 to n, compute the number of 1-bits in its binary representation.

n = 5
-> [0, 1, 1, 2, 1, 2]      # 0=0b0, 1=0b1, 2=0b10, 3=0b11, 4=0b100, 5=0b101

Return the full table. Counting each number's bits independently is O(nlogn)O(n \log n), aim for O(n)O(n) total.

Show a hint

What does i & (i - 1) do to the binary representation of i?

Your answer

This one is open-ended. Work it through, then check your reasoning against the full solution.

More Coding questions