Bird
Raised Fist0
Interview Prepbit-manipulationeasyAmazonGoogleApple

Number of 1 Bits (Hamming Weight)

Choose your preparation mode4 modes available
📋
Problem

Imagine you are working on a network packet analyzer that needs to quickly count how many flags are set in a packet header represented as a 32-bit integer.

Write a function that takes an unsigned integer and returns the number of '1' bits it has (also known as the Hamming weight). Input is a 32-bit unsigned integer. Output is an integer count of set bits.

The input is a 32-bit unsigned integer.You must handle the input efficiently.
Edge cases: n = 0 → output 0 (no bits set)n = 4294967295 (all bits set) → output 32n = 1 (only least significant bit set) → output 1
</>
IDE
def hammingWeight(n: int) -> int:public int hammingWeight(int n)int hammingWeight(unsigned int n)function hammingWeight(n)
def hammingWeight(n: int) -> int:
    # Write your solution here
    pass
class Solution {
    public int hammingWeight(int n) {
        // Write your solution here
        return 0;
    }
}
#include <vector>
using namespace std;

int hammingWeight(unsigned int n) {
    // Write your solution here
    return 0;
}
function hammingWeight(n) {
    // Write your solution here
}
Coming soon
0/9
Common Bugs to Avoid
Wrong: 0Not counting any bits or returning zero prematurely.✅ Ensure loop iterates 32 times and sums n & 1 each iteration.
Wrong: 31Off-by-one error when input has all bits set (32 bits).✅ Iterate full 32 bits and do not stop early; count all bits correctly.
Wrong: Wrong count for highest bit set input (e.g., 0 instead of 1)Ignoring or missing the most significant bit during counting.✅ Ensure loop covers all 32 bits including the highest bit.
Wrong: Incorrect count for alternating bits pattern (e.g., 15 instead of 16)Miscounting bits due to incorrect bitwise operations or skipping bits.✅ Use Kernighan’s algorithm or carefully check each bit in a loop.
Wrong: Timeout or no outputInefficient brute force approach causing TLE on large inputs.✅ Implement Brian Kernighan’s algorithm to reduce iterations to number of set bits.
✓
Test Cases
t1_01basic
Input{"n":11}
Expected3

The binary representation of 11 is 00000000000000000000000000001011 which has three '1' bits at positions 0, 1, and 3.

t1_02basic
Input{"n":29}
Expected4

29 in binary is 00000000000000000000000000011101 which has four '1' bits at positions 0, 2, 3, and 4.

t2_01edge
Input{"n":0}
Expected0

Zero has no bits set, so the count is 0.

t2_02edge
Input{"n":4294967295}
Expected32

4294967295 is 32 bits all set to 1, so the count is 32.

t2_03edge
Input{"n":2147483648}
Expected1

2147483648 is 10000000000000000000000000000000 in binary with only the most significant bit set.

t3_01corner
Input{"n":15}
Expected4

15 in binary is 00000000000000000000000000001111 with four bits set.

t3_02corner
Input{"n":2147483647}
Expected31

2147483647 is 01111111111111111111111111111111 in binary with 31 bits set.

t3_03corner
Input{"n":2863311530}
Expected16

2863311530 in binary is 10101010101010101010101010101010 with exactly 16 bits set.

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

Input is the maximum 32-bit unsigned integer with all bits set (n=4294967295). The solution must run in O(1) or O(k) time where k is number of set bits, completing within 2 seconds.

Practice

(1/5)
1. Consider the following Python function to find two missing numbers from 1 to n using XOR partitioning. Given n = 4 and arr = [1, 3], what is the final returned list?
easy
A. [4, 2]
B. [1, 3]
C. [2, 4]
D. [3, 1]

Solution

  1. Step 1: Compute xor_all

    xor_all = 1^2^3^4 ^ 1^3 = (1^1)^(2)^(3^3)^(4) = 2 ^ 4 = 6 (binary 110)
  2. Step 2: Find rightmost set bit and partition

    set_bit = 6 & (-6) = 2 (binary 010). Partition numbers by this bit: Group 1 (bit set): numbers with bit 2 set -> 2, 3 Group 2 (bit not set): 1, 4 XOR group 1: 2 ^ 3 ^ (arr nums with bit set: 3) = 2 ^ 3 ^ 3 = 2 XOR group 2: 1 ^ 4 ^ (arr nums with bit not set: 1) = 1 ^ 4 ^ 1 = 4 So missing numbers are [2, 4].
  3. Final Answer:

    Option C -> Option C
  4. Quick Check:

    Output matches expected missing numbers [OK]
Hint: Trace XOR and partition by rightmost set bit carefully [OK]
Common Mistakes:
  • Misinterpret bit masking for partition
  • Mixing order of XOR operations
  • Confusing missing numbers with present ones
2. The following code attempts to count set bits for all numbers from 0 to n using Brian Kernighan's trick. Identify the line containing the subtle bug that causes incorrect results.
def countBits(n):
    res = []
    for i in range(1, n + 1):
        count = 0
        x = i
        while x:
            x &= x - 1
            count += 1
        res.append(count)
    return res
medium
A. Line 3: for i in range(1, n + 1):
B. Line 2: res = []
C. Line 5: while x:
D. Line 7: res.append(count)

Solution

  1. Step 1: Check loop range correctness

    The loop starts from 1, missing 0, so the count for 0 is never computed or appended.
  2. Step 2: Consequence of missing 0

    Result array length is n instead of n+1, causing mismatch and incorrect output for input including 0.
  3. Final Answer:

    Option A -> Option A
  4. Quick Check:

    Including 0 is required to match problem specification [OK]
Hint: Loop must start at 0 to include zero count [OK]
Common Mistakes:
  • Starting loop at 1 instead of 0
  • Appending before counting
  • Incorrect while condition
3. Identify the bug in the following code that attempts to check if a number is a power of two:
def isPowerOfTwo(n: int) -> bool:
    while n % 2 == 0:
        n //= 2
    return n == 1
What is the issue?
medium
A. The return statement should check n == 0 instead of n == 1
B. The loop condition should be n > 1 instead of n % 2 == 0
C. Using integer division //= 2 causes infinite loops for odd numbers
D. The code does not handle zero or negative inputs, leading to incorrect results

Solution

  1. Step 1: Analyze input handling

    The code does not check if n is positive before the loop, so zero or negative inputs cause incorrect behavior.
  2. Step 2: Consequence of missing check

    For n=0 or negative, the loop condition n % 2 == 0 may cause infinite loop or wrong return value.
  3. Final Answer:

    Option D -> Option D
  4. Quick Check:

    Proper input validation is required to avoid incorrect results [OK]
Hint: Always check n > 0 before division loops [OK]
Common Mistakes:
  • Forgetting zero/negative input checks
  • Confusing loop condition with termination condition
4. What is the time complexity of the optimal XOR and partition approach to find two unique numbers in an array of size n?
medium
A. O(n log n) due to sorting step
B. O(n) because it traverses the array a constant number of times
C. O(n^2) because of nested loops in partitioning
D. O(n) but uses O(n) extra space for partitions

Solution

  1. Step 1: Identify loops in the algorithm

    The algorithm traverses the array twice: once to XOR all elements, once to partition and XOR groups.
  2. Step 2: Analyze time and space complexity

    Each traversal is O(n), no nested loops. Space used is constant (variables only), no extra arrays.
  3. Final Answer:

    Option B -> Option B
  4. Quick Check:

    Two linear passes, constant space [OK]
Hint: Two passes over array -> O(n) time, O(1) space [OK]
Common Mistakes:
  • Confusing with sorting complexity
  • Assuming nested loops in partition
  • Forgetting constant space usage
5. Consider the following buggy implementation of sum of two integers without + operator. Which line contains the subtle bug that causes incorrect results or infinite recursion?
medium
A. Line 3: base case condition if b == 0
B. Line 6: sum_ calculation using XOR and MASK
C. Line 8: recursive call with sum_ and carry
D. Line 7: carry calculation missing left shift

Solution

  1. Step 1: Analyze carry calculation

    Carry must be (a & b) << 1 to shift carry bits to correct position.
  2. Step 2: Identify missing left shift causes infinite recursion

    Without shifting, carry never reduces to zero, causing infinite recursion or wrong sum.
  3. Final Answer:

    Option D -> Option D
  4. Quick Check:

    Carry missing shift breaks carry propagation [OK]
Hint: Carry must be shifted left by 1 bit [OK]
Common Mistakes:
  • Forgetting carry shift
  • Incorrect base case
  • Not masking intermediate results
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