KatInterview

338. Counting Bits

EasySolutions in Python, Java, C++, TypeScript

Read the full problem statement on LeetCode and try it first. Below is how to approach it in an interview, followed by a complete answer in each language.

Approach

The core task is to compute the number of set bits (1s) in the binary representation for every integer from 0 to n. A naive solution would involve iterating through each number i and counting its bits, leading to an O(n log n) complexity. The challenge is to find a linear time O(n) solution, which suggests using dynamic programming to leverage previously computed results.

Solution

Counting Bits in Python

class Solution:
    def countBits(self, n: int) -> List[int]:
        # Create a result list of size n + 1, initialized to 0.
        # ans[0] will be 0.
        ans = [0] * (n + 1)
        
        # Iterate from 1 to n.
        for i in range(1, n + 1):
            # The number of 1s in i is the number of 1s in i // 2
            # plus the last bit of i.
            # i >> 1 is equivalent to i // 2.
            # i & 1 is 1 if i is odd, 0 if i is even.
            ans[i] = ans[i >> 1] + (i & 1)
            
        return ans

Counting Bits in Java

class Solution {
    public int[] countBits(int n) {
        // Create a result array of size n + 1.
        // The array is initialized to zeros by default, so ans[0] is 0.
        int[] ans = new int[n + 1];
        
        // Iterate from 1 to n.
        for (int i = 1; i <= n; ++i) {
            // The number of 1s in i is the number of 1s in i/2
            // plus the last bit of i.
            // i >> 1 is equivalent to i / 2.
            // i & 1 is 1 if i is odd, 0 if i is even.
            ans[i] = ans[i >> 1] + (i & 1);
        }
        
        return ans;
    }
}

Counting Bits in C++

class Solution {
public:
    vector<int> countBits(int n) {
        // Create a result vector of size n + 1, initialized to 0.
        // ans[0] is automatically 0.
        vector<int> ans(n + 1, 0);
        
        // Iterate from 1 to n.
        for (int i = 1; i <= n; ++i) {
            // The number of 1s in i is the number of 1s in i/2
            // plus the last bit of i.
            // i >> 1 is equivalent to i / 2.
            // i & 1 is 1 if i is odd, 0 if i is even.
            ans[i] = ans[i >> 1] + (i & 1);
        }
        
        return ans;
    }
};

Counting Bits in TypeScript

function countBits(n: number): number[] {
    // Create a result array of size n + 1, initialized to 0.
    const ans = new Array(n + 1).fill(0);
    
    // Iterate from 1 to n.
    for (let i = 1; i <= n; i++) {
        // The number of 1s in i is the number of 1s in i/2
        // plus the last bit of i.
        // i >> 1 is equivalent to Math.floor(i / 2).
        // i & 1 is 1 if i is odd, 0 if i is even.
        ans[i] = ans[i >> 1] + (i & 1);
    }
    
    return ans;
};

Preparing for interviews beyond LeetCode? Practise system design, SQL and behavioral questions with an in-browser runner on KatInterview.

LeetCode is a trademark of LeetCode LLC. KatInterview is not affiliated with LeetCode.