Given a non negative integer number num. For every numbers i in the range 0 ≤ i ≤ num calculate the number of 1’s in their binary representation and return them as an array.

Example:
For num = 5 you should return [0,1,1,2,1,2].

It is very easy to come up with a solution with run time O(n*sizeof(integer)). But can you do it in linear time O(n) /possibly in a single pass?
Space complexity should be O(n).
Can you do it like a boss? Do it without using any builtin function like __builtin_popcount in c++ or in any other language.

Bits     Nums

0:        0

1:         1 (1 + 0)

2:        10 (1 << 1  + 0), 11(1 << 1 + 1)

3:        100(1 << 2 + 0), 101(1 << 2 + 1), 110(1 << 2 + 10), 111(1 << 2 + 11)

Easy to find that: for every new bit i, it just add 1 << (i – 1) to all bit numbers before i bits. For example, 110, which has 3 bits, is added by 100 (1 << 2) and 10(first number which has 2 bits). Solution: (Time and space complexity are both linear)

``````
int* countBits(int num, int* returnSize) {
*returnSize = num + 1;
int* res = (int*)malloc((*returnSize) * sizeof(int));
res[0] = 0;
int bit = 1, tempNum = 0;

while(tempNum <= num)
{
int bitMax = 1 << (bit - 1);
for(int i = tempNum, j = 0; i < bitMax; ++i, ++j)
{
if(i > num) return res;
if(i != 0) res[i] = res[j] + 1;
}
tempNum = bitMax;
++bit;
}

return res;
}
128ms
``````