Count Set Bits Brian Kernighan Algorithm in DSA C# - Time & Space Complexity
We want to understand how fast the Brian Kernighan algorithm counts the number of 1s in a number's binary form.
How does the time taken change as the number gets bigger?
Analyze the time complexity of the following code snippet.
int CountSetBits(int n) {
int count = 0;
while (n > 0) {
n = n & (n - 1);
count++;
}
return count;
}
This code counts how many bits are set to 1 in the binary form of the number n.
Identify the loops, recursion, array traversals that repeat.
- Primary operation: The while loop runs once for each set bit in n.
- How many times: Equal to the number of 1s in the binary representation of n.
Each loop removes one set bit, so the number of loops depends on how many 1s are in n.
| Input Size (n) | Approx. Operations (set bits) |
|---|---|
| 10 (binary 1010) | 2 |
| 15 (binary 1111) | 4 |
| 1023 (binary 1111111111) | 10 |
Pattern observation: The time grows with the number of 1 bits, not the total bits or the value of n.
Time Complexity: O(k) where k is the number of set bits in n.
This means the algorithm runs faster if there are fewer 1s, and slower if there are many 1s.
[X] Wrong: "The loop always runs for all bits in the number (like 32 or 64 times)."
[OK] Correct: The loop only runs as many times as there are 1s, so it can be much faster than checking every bit.
Understanding this algorithm shows you can find efficient ways to solve problems by focusing on what really matters, like the number of set bits instead of total bits.
"What if we changed the input to always have only one set bit? How would the time complexity change?"
Practice
Solution
Step 1: Understand the algorithm's main operation
The Brian Kernighan algorithm works by clearing the least significant set bit in each iteration.Step 2: Effect of clearing bits on counting set bits
Each time it clears a set bit, it increments the count until the number becomes zero.Final Answer:
It repeatedly clears the least significant set bit until the number becomes zero. -> Option DQuick Check:
Clearing bits counts set bits [OK]
- Counting zeros instead of ones
- Using string conversion to count bits
- Shifting bits without clearing
Solution
Step 1: Identify the bit clearing operation
The expression n = n & (n - 1) clears the least significant set bit in n.Step 2: Verify other options
Other options perform different bitwise operations that do not clear the least significant set bit.Final Answer:
n = n & (n - 1); -> Option AQuick Check:
Use n & (n-1) to clear least set bit [OK]
- Using OR instead of AND
- Using XOR with n+1 incorrectly
- Using left shift which moves bits
int countSetBits(int n) {
int count = 0;
while (n > 0) {
n = n & (n - 1);
count++;
}
return count;
}
Console.WriteLine(countSetBits(13));Solution
Step 1: Convert 13 to binary and count set bits
13 in binary is 1101, which has three set bits (1s).Step 2: Apply Brian Kernighan's algorithm
Each iteration clears one set bit, so the loop runs 3 times, incrementing count to 3.Final Answer:
3 -> Option AQuick Check:
Binary 1101 has 3 ones [OK]
- Counting total bits instead of set bits
- Misunderstanding bitwise AND operation
- Off-by-one errors in loop
int countSetBits(int n) {
int count = 0;
while (n != 0) {
n = n & (n + 1);
count++;
}
return count;
}Solution
Step 1: Check the bit clearing expression
The code uses n & (n + 1), which does not clear the least significant set bit correctly.Step 2: Correct expression for clearing bits
The correct expression is n & (n - 1) to clear the least significant set bit.Final Answer:
Using n & (n + 1) instead of n & (n - 1) -> Option BQuick Check:
Use n & (n-1) to clear bits [OK]
- Using n & (n + 1) which is incorrect
- Confusing loop conditions
- Forgetting to initialize count
Solution
Step 1: Understand the need for efficiency
Counting set bits for many integers can be slow if done sequentially.Step 2: Use parallel processing with Brian Kernighan's algorithm
Running the efficient bit counting algorithm concurrently on multiple integers speeds up processing.Final Answer:
Use Brian Kernighan's algorithm inside a parallel loop to count bits for each integer concurrently. -> Option CQuick Check:
Parallel + efficient algorithm = best performance [OK]
- Using string conversion which is slow
- Sequential bit shifting which is less efficient
- Ignoring concurrency for large data
Ready to prove it?
Pass the test and this pattern moves unknown
