Bird
Raised Fist0
DSA Pythonprogramming~20 mins

Count Set Bits Brian Kernighan Algorithm in DSA Python - Practice Problems & Challenges

Choose your learning style10 modes available
Challenge - 5 Problems
🎖️
Brian Kernighan Bit Master
Get all challenges correct to earn this badge!
Test your skills under time pressure!
❓ Predict Output
intermediate
2:00remaining
Output of Brian Kernighan's Algorithm for Counting Set Bits
What is the output of the following code that counts set bits using Brian Kernighan's algorithm?
DSA Python
def count_set_bits(n):
    count = 0
    while n:
        n &= (n - 1)
        count += 1
    return count

print(count_set_bits(29))
A4
B5
C3
D6
Attempts:
2 left
💡 Hint
Count how many times the loop runs by removing the rightmost set bit each time.
❓ Predict Output
intermediate
2:00remaining
Result of Counting Set Bits for Zero
What is the output of the code when counting set bits of zero using Brian Kernighan's algorithm?
DSA Python
def count_set_bits(n):
    count = 0
    while n:
        n &= (n - 1)
        count += 1
    return count

print(count_set_bits(0))
ANone
B1
C0
DError
Attempts:
2 left
💡 Hint
Zero has no set bits.
🧠 Conceptual
advanced
2:00remaining
Why Brian Kernighan's Algorithm is Efficient
Why is Brian Kernighan's algorithm more efficient than checking each bit individually to count set bits?
AIt converts the number to a string and counts '1's.
BIt uses recursion to reduce time complexity.
CIt uses a lookup table for all possible bit patterns.
DIt loops only as many times as there are set bits, not total bits.
Attempts:
2 left
💡 Hint
Think about how many times the loop runs compared to total bits.
🔧 Debug
advanced
2:00remaining
Identify the Error in Modified Brian Kernighan's Code
What error will occur when running this modified code to count set bits?
DSA Python
def count_set_bits(n):
    count = 0
    while n > 0:
        n = n & (n + 1)
        count += 1
    return count

print(count_set_bits(4))
AInfinite loop
BSyntaxError
CReturns 0
DCorrect output 4
Attempts:
2 left
💡 Hint
Check how n changes each iteration with n & (n + 1).
🚀 Application
expert
3:00remaining
Number of Integers with Exactly k Set Bits in Range
How many integers between 0 and 15 (inclusive) have exactly 2 set bits? Use Brian Kernighan's algorithm to count set bits.
A5
B6
C4
D7
Attempts:
2 left
💡 Hint
List numbers 0 to 15 and count set bits for each.

Practice

(1/5)
1. What does the Brian Kernighan algorithm do when counting set bits in a number?
easy
A. It shifts the number to the right until it becomes zero without counting bits.
B. It counts the total number of digits in the number.
C. It converts the number to a string and counts the characters.
D. It repeatedly clears the least significant set bit until the number becomes zero.

Solution

  1. Step 1: Understand the algorithm's main operation

    The Brian Kernighan algorithm clears the least significant set bit in each iteration by doing n = n & (n-1).
  2. Step 2: Effect of clearing bits

    Each clearing reduces the number of set bits by one until the number becomes zero, counting how many bits were set.
  3. Final Answer:

    It repeatedly clears the least significant set bit until the number becomes zero. -> Option D
  4. Quick Check:

    Clearing bits counts set bits [OK]
Hint: Clear rightmost set bit repeatedly to count bits [OK]
Common Mistakes:
  • Thinking it counts all digits, not just set bits
  • Confusing bit shifting with bit clearing
  • Counting characters in string form of number
2. Which of the following is the correct syntax to clear the least significant set bit in Python using Brian Kernighan's method?
easy
A. n = n & (n - 1)
B. n = n | (n - 1)
C. n = n ^ (n - 1)
D. n = n + (n - 1)

Solution

  1. Step 1: Identify the bit clearing operation

    The correct operation to clear the least significant set bit is n = n & (n - 1).
  2. Step 2: Understand why other options are incorrect

    Using OR, XOR, or addition does not clear the least significant set bit correctly.
  3. Final Answer:

    n = n & (n - 1) -> Option A
  4. Quick Check:

    Bit clear uses AND with n-1 [OK]
Hint: Use AND with n minus one to clear bits [OK]
Common Mistakes:
  • Using OR instead of AND
  • Using XOR which toggles bits
  • Adding numbers instead of bitwise operations
3. What is the output of the following Python code using Brian Kernighan's algorithm?
def count_set_bits(n):
    count = 0
    while n:
        n = n & (n - 1)
        count += 1
    return count

print(count_set_bits(13))
medium
A. 3
B. 5
C. 4
D. 2

Solution

  1. Step 1: Convert 13 to binary

    13 in binary is 1101, which has three set bits (1s).
  2. Step 2: Count set bits using the algorithm

    Each iteration clears one set bit: 1101 -> 1100 -> 1000 -> 0000, total 3 times.
  3. Final Answer:

    3 -> Option A
  4. Quick Check:

    Binary 1101 has 3 set bits [OK]
Hint: Count 1s in binary of number [OK]
Common Mistakes:
  • Counting total bits instead of set bits
  • Miscounting binary digits
  • Confusing decimal with binary
4. Find the error in the following code that tries to count set bits using Brian Kernighan's algorithm:
def count_set_bits(n):
    count = 0
    while n > 0:
        n = n & (n + 1)
        count += 1
    return count

print(count_set_bits(7))
medium
A. Loop condition should be n != 0
B. Missing initialization of count variable
C. Using n & (n + 1) instead of n & (n - 1)
D. Using addition instead of bitwise AND

Solution

  1. Step 1: Identify the bit clearing operation

    The code uses n & (n + 1), which does not clear the least significant set bit correctly.
  2. Step 2: Correct operation for clearing bits

    The correct operation is n = n & (n - 1) to clear the rightmost set bit.
  3. Final Answer:

    Using n & (n + 1) instead of n & (n - 1) -> Option C
  4. Quick Check:

    Use n & (n - 1) to clear bits [OK]
Hint: Use n & (n - 1), not n & (n + 1) [OK]
Common Mistakes:
  • Using n & (n + 1) which is incorrect
  • Confusing loop condition syntax
  • Forgetting to initialize count
5. Given a list of integers, which code snippet correctly uses Brian Kernighan's algorithm to return a list of counts of set bits for each number?
nums = [3, 5, 7]

A) def count_bits_list(nums):
       return [bin(n).count('1') for n in nums]

B) def count_bits_list(nums):
       def count_set_bits(n):
           count = 0
           while n:
               n = n & (n - 1)
               count += 1
           return count
       return [count_set_bits(n) for n in nums]

C) def count_bits_list(nums):
       return [sum(int(d) for d in str(n)) for n in nums]

D) def count_bits_list(nums):
       return [len(str(n)) for n in nums]
hard
A. Option A uses built-in count of '1's in binary string.
B. Option B uses Brian Kernighan's algorithm correctly.
C. Option C sums digits of decimal string, not bits.
D. Option D counts decimal digits, not bits.

Solution

  1. Step 1: Analyze the code snippets

    The first snippet uses Python's bin(n).count('1'), which counts set bits but not Brian Kernighan's algorithm. The second snippet implements the algorithm correctly using a while loop that clears the least significant set bit with n = n & (n - 1). The third sums the decimal digits, which is incorrect for bits. The fourth counts the length of the decimal string, also incorrect.
  2. Step 2: Confirm correct implementation

    The second snippet defines count_set_bits using n = n & (n - 1) in a loop and applies it to each number via list comprehension, which is the proper use of Brian Kernighan's algorithm.
  3. Final Answer:

    Option B uses Brian Kernighan's algorithm correctly. -> Option B
  4. Quick Check:

    Correctly uses n & (n-1) loop [OK]
Hint: Use n & (n - 1) loop inside list comprehension [OK]
Common Mistakes:
  • Using string digit sums instead of bits
  • Counting decimal digits instead of set bits
  • Confusing built-in binary count with algorithm
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