Given a positive number n, construct an integer array of length n where each index stores the count of 1’s in the binary representation of the index.

For example,

Input: n = 5
 
Output: [0, 1, 1, 2, 1]
 
Explanation:
 
0th index is 0 in binary
1st index is 1 in binary
2nd index is 10 in binary
3rd index is 11 in binary
4th index is 100 in binary

The problem of counting the set bits in a binary number can be divided into two parts: checking the last bit of the number and counting the set bits in the remaining bits. For example, a binary number 10101101 can be split into the last bit (1) and the remaining bits (1010110). The last bit of n can be obtained using the expression n & 1 (or n % 2), and the remaining bits can be obtained using the expression n >> 1 (or n / 2). Taking this into account, we can formulate the recurrence relation T[n] for counting the set bits in n as follows: 

T[n] = T[n >> 1] + (n & 1)

 
Following is the C++, Java, and Python program that implements the above recurrence:

C++


Download  Run Code

Output:

0 1 1 2 1

Java


Download  Run Code

Output:

[0, 1, 1, 2, 1]

Python


Download  Run Code

Output:

[0, 1, 1, 2, 1]

 
Alternatively, we can count the set bits of a number n using Brian Kernighan’s algorithm. The problem can be defined by the following recurrence relation.

T[n] = T[n & (n-1)] + 1

 
Here, the expression n & (n-1) unsets the rightmost set bit of a number n. It works as the expression n-1 flips all the bits after the rightmost set bit of n, including the rightmost set bit itself. As a consequence, n & (n-1) unsets the last set bit of n. Following is the C++, Java, and Python implementation based on the idea:

C++


Download  Run Code

Output:

0 1 1 2 1

Java


Download  Run Code

Output:

[0, 1, 1, 2, 1]

Python


Download  Run Code

Output:

[0, 1, 1, 2, 1]

The time complexity of the above solutions is O(n).