Bird
Raised Fist0
Interview Prepbit-manipulationeasyAmazonFacebookGoogle

Counting Bits (0 to N)

Choose your preparation mode4 modes available
📋
Problem

Imagine you are designing a system that needs to quickly count the number of set bits in all numbers from 0 up to a given number N, such as for optimizing storage or network protocols.

Given a non-negative integer n, return an array of length n + 1 where the ith element is the number of 1 bits in the binary representation of the integer i.

1 ≤ n ≤ 10^5
Edge cases: n = 0 → [0]n = 1 → [0,1]n = 2 → [0,1,1]
</>
IDE
def countBits(n: int) -> list:public int[] countBits(int n)vector<int> countBits(int n)function countBits(n)
def countBits(n):
    # Write your solution here
    pass
class Solution {
    public int[] countBits(int n) {
        // Write your solution here
        return new int[0];
    }
}
#include <vector>
using namespace std;

vector<int> countBits(int n) {
    // Write your solution here
    return {};
}
function countBits(n) {
    // Write your solution here
}
Coming soon
0/9
Common Bugs to Avoid
Wrong: [0,1,1,1,1,2]Greedy approach subtracting largest power of two but not counting bits correctly.✅ Use dp[i] = dp[i >> 1] + (i & 1) instead of greedy subtraction.
Wrong: [0]Fails to handle n > 0, returns only dp[0].✅ Initialize dp array of size n+1 and fill all values up to n.
Wrong: [0,1,1]Off-by-one error causing missing last element for n=2.✅ Loop from 0 to n inclusive and return dp of length n+1.
Wrong: Timeout or no outputBrute force bit counting for each number causing O(n log n) time complexity.✅ Use O(n) DP approach with dp[i] = dp[i >> 1] + (i & 1).
✓
Test Cases
t1_01basic
Input{"n":5}
Expected[0,1,1,2,1,2]

Binary representations: 0(0),1(1),2(10),3(11),4(100),5(101). Counting 1s gives the output.

t1_02basic
Input{"n":3}
Expected[0,1,1,2]

Binary: 0(0),1(1),2(10),3(11). Counts of 1 bits are [0,1,1,2].

t2_01edge
Input{"n":0}
Expected[0]

Only number 0, which has 0 set bits.

t2_02edge
Input{"n":1}
Expected[0,1]

Numbers 0 and 1 have 0 and 1 set bits respectively.

t2_03edge
Input{"n":2}
Expected[0,1,1]

Numbers 0,1,2 have bit counts 0,1,1 respectively.

t3_01corner
Input{"n":7}
Expected[0,1,1,2,1,2,2,3]

Binary 0 to 7: counts of 1 bits are as shown.

t3_02corner
Input{"n":8}
Expected[0,1,1,2,1,2,2,3,1]

Binary 0 to 8: counts of 1 bits including exact power of two boundary.

t3_03corner
Input{"n":15}
Expected[0,1,1,2,1,2,2,3,1,2,2,3,2,3,3,4]

Binary 0 to 15: counts of 1 bits for all 4-bit numbers.

t4_01performance
Input{"n":100000}
⏱ Performance - must finish in 2000ms

n=100000 tests O(n) DP solution performance; brute force O(n log n) may time out.

Practice

(1/5)
1. Given the following Python code, what is the output of isPowerOfFour(16)?
easy
A. True
B. False
C. Raises an error due to floating point precision
D. None

Solution

  1. Step 1: Calculate log2(16)

    log2(16) = 4, dividing by 2 gives 2.0.
  2. Step 2: Check if 2.0 equals int(2.0)

    2.0 == 2 is True, so the function returns True.
  3. Final Answer:

    Option A -> Option A
  4. Quick Check:

    16 is 4^2, so output True is expected [OK]
Hint: log2(16)/2 = 2.0 equals int(2) -> True
Common Mistakes:
  • Assuming floating point error causes failure
  • Confusing power of two with power of four
2. What is the time complexity of generating an n-bit Gray code sequence using the optimal bitwise formula [i ^ (i >> 1) for i in range(1 << n)]?
medium
A. O(n)
B. O((2^n)!)
C. O(n * 2^n)
D. O(2^n)

Solution

  1. Step 1: Analyze the loop iteration count

    The list comprehension iterates over all integers from 0 to 2^n - 1, so 2^n iterations.
  2. Step 2: Analyze work per iteration

    Each iteration performs constant time bitwise operations (XOR and right shift), so O(1) per iteration.
  3. Final Answer:

    Option D -> Option D
  4. Quick Check:

    Total time is proportional to 2^n, not multiplied by n or factorial [OK]
Hint: Loop runs 2^n times with O(1) work each [OK]
Common Mistakes:
  • Confusing n with 2^n and claiming O(n)
  • Assuming bitwise operations cost O(n)
  • Mistaking factorial complexity from brute force backtracking
3. Consider this buggy code snippet for finding two unique numbers. Which line contains the subtle bug?
medium
A. Line 8: set_bit calculation
B. Line 6: xor calculation loop
C. Line 3: xor initialization
D. Line 12: partitioning condition

Solution

  1. Step 1: Identify how set_bit is computed

    Correct approach uses set_bit = xor & (-xor) to isolate rightmost set bit. Here, set_bit = xor misses this step.
  2. Step 2: Understand impact of bug

    Without isolating rightmost set bit, partitioning fails, XOR groups won't separate unique numbers correctly.
  3. Final Answer:

    Option A -> Option A
  4. Quick Check:

    Bug in set_bit calculation breaks partitioning [OK]
Hint: Isolate rightmost set bit with xor & (-xor) [OK]
Common Mistakes:
  • Using xor directly as set_bit
  • Breaking early before full XOR
  • Misusing partition condition
4. Suppose the problem changes: you want to find the maximum product of word lengths where words can be reused multiple times (i.e., pairs can be the same word twice if allowed). Which modification to the optimal bitmasking approach correctly handles this variant?
hard
A. Precompute bitmasks and lengths, then for each word, consider its square length if it has no repeated characters, else zero; finally, check pairs as before including identical indices.
B. Remove the pruning condition and check all pairs including identical indices without overlap check.
C. Allow i and j to be equal in the nested loops and check bitmask overlap as before.
D. Use a frequency map of words and multiply lengths by frequency to find maximum product.

Solution

  1. Step 1: Understand reuse of words

    Reusing the same word twice is only valid if the word has no repeated characters (so no overlap with itself).
  2. Step 2: Modify approach

    Precompute bitmasks and lengths; for each word, consider its length squared if it has unique characters (bitmask check for duplicates). Then check pairs including identical indices.
  3. Step 3: Why other options fail

    Allowing i=j without checking duplicates or removing pruning leads to incorrect or inefficient results; frequency map is irrelevant here.
  4. Final Answer:

    Option A -> Option A
  5. Quick Check:

    Considering squares for unique words and pairs covers reuse correctly [OK]
Hint: Reuse allowed only if word has unique chars [OK]
Common Mistakes:
  • Allowing reuse without checking duplicates in word
  • Removing pruning causing inefficiency
  • Using frequency maps which don't apply here
5. If the input array can contain negative numbers, which modification is necessary for the optimal XOR and partition approach to correctly find the two unique numbers?
hard
A. No modification needed; the current approach works for negative numbers as is.
B. Use absolute values of numbers for XOR and partitioning to avoid sign issues.
C. Sort the array first to handle negative numbers before applying XOR partitioning.
D. Use set_bit = xor & (-xor) carefully, ensuring two's complement representation is handled correctly.

Solution

  1. Step 1: Understand bitwise operations with negative numbers

    Negative numbers use two's complement; -xor computes two's complement correctly, so set_bit = xor & (-xor) works if implemented carefully.
  2. Step 2: Identify necessary care

    Ensure language and environment handle negative bitwise operations properly; no need to sort or use absolute values.
  3. Final Answer:

    Option D -> Option D
  4. Quick Check:

    Correct handling of two's complement is key for negative numbers [OK]
Hint: Two's complement handles negative bits; no sorting needed [OK]
Common Mistakes:
  • Assuming XOR fails on negatives
  • Sorting wastes time
  • Using absolute values breaks uniqueness
Recommended

Ready to prove it?

Pass the test and this pattern moves unknown strong while earning +1 Grip toward your certificate.

10 questions~5 mineasy hard