For every number i from 0 to n, count the 1s in i written in binary, and return the n + 1 counts as a list, the count for i at index i. The expected solution computes each entry from earlier entries rather than counting every number from scratch.
Examples
Example 1:
Input: n = 2
Output: [0,1,1]
Example 2:
Input: n = 5
Output: [0,1,1,2,1,2]
Explanation: 0,1,10,11,100,101.
Example 3:
Input: n = 0
Output: [0]
Constraints
0 <= n <= 10^5
Prerequisites
Binary and two's complement — how a negative number is stored, and what a shift does at the edges. The trick worth memorising: n & (n-1) clears the lowest set bit.
How to think about it
1. Reuse the Answer for n >> 1 Optimal
Intuition
Shift i right by one and its last bit drops off: i >> 1 is i with that bit gone. It is smaller than i, so its count is already in the list, and i's count is that count plus the bit that dropped, i & 1. 6 = 110 shifts to 3 = 11, which has two 1s, and drops a 0: 2. 7 = 111 shifts to 3 too, and drops a 1: 3. So bits[0] is 0 and every other entry is one lookup and one addition, where counting each number from scratch walks all its bits. Shift off the last bit, and add that bit to the shifted number's count.
Algorithm
1. Make bits, a list of n + 1 zeros: bits[0] stays 0. 2. For each i from 1 to n, set bits[i] to bits[i >> 1] + (i & 1). 3. Return bits.
Time & Space
Time O(n). Space O(n) for the output.
2. Count Every Number from Scratch
Intuition
Each number's 1s can be counted on their own, one bit at a time. x & 1 is x's last bit: 1 when it is set, 0 when it is not, so adding it to a count counts the set bits as they pass. Shifting x right drops the bit just tested and brings the next one down, until x is 0, and 0 counts none. Do that for a copy of every i from 0 to n, and bits[i] is its count. Counting 6 = 110 from scratch takes three steps, a step a bit, and 7 = 111 takes three too. Every number walks all its bits, so the work grows like n times the bits in a number, where reusing the count of i >> 1 takes one lookup a number. In Java, >> is enough: no i is negative. Count every number from scratch, testing the last bit and shifting right.
Algorithm
1. Make bits, a list of n + 1 zeros. 2. For each i from 0 to n, start a count at 0 and copy i to x; while x is not 0, add x & 1, its last bit, to the count, and shift x right by one. Set bits[i] to the count. 3. Return bits.
Time & Space
Time O(n log n): every number walks all its bits, at most 17. Space O(n) for the output.