Counting Bits

Problem

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].

Follow up:

  • 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.

Solution

Solution using bitCount(): O(nlgn) time O(1) space

public class Solution {

    public int[] countBits(int num) {
        int[] res = new int[num + 1];
        for (int i = 0; i <= num; i++) res[i] = bitCount(i);
        return res;
    }

    private int bitCount(int n) {
        int count = 0;
        while (n != 0) {
            count += n & 1;
            n = n >> 1;
        }
        return count;
    }
}

DP Solution: O(n) time O(1) space

public class Solution {
    public int[] countBits(int num) {
        int[] res = new int[num + 1];
        for (int i = 0; i <= num; i++) res[i] = res[i / 2] + i % 2; //i / 2 == i >> 1 
        return res;
    }
}

Analysis

In the dp solution, we construct dp[i] by making use of previous value in the array
That is, dp[i] = dp[i / 2] + i % 2
This is because we can count bits using its previous flat binary value + remainder of 2

results matching ""

    No results matching ""