Count Set Bits Brian Kernighan Algorithm in DSA Java - Time & Space Complexity
We want to understand how fast the Brian Kernighan algorithm counts the number of 1s in a binary number.
How does the time taken change as the number gets bigger?
Analyze the time complexity of the following code snippet.
public 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 by repeatedly turning off the rightmost set bit.
- 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 operations depends on how many 1s are in n.
| Input Size (n) | Approx. Operations (set bits) |
|---|---|
| 10 (1010 binary) | 2 |
| 100 (1100100 binary) | 3 |
| 1000 (1111101000 binary) | 6 |
Pattern observation: The time grows with the number of 1s, not the total bits or value size.
Time Complexity: O(k)
This means the time depends on the count of set bits (k) in the number, not the total number of bits.
[X] Wrong: "The loop runs for all bits of the number, so it is O(log n)."
[OK] Correct: The loop only runs once per set bit, so if the number has few 1s, it runs faster than checking every bit.
Knowing this algorithm shows you can optimize bit counting by focusing on set bits, a useful skill for efficient low-level coding.
"What if we changed the input to always have half of its bits set? 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
Each clearing reduces the number of set bits by one 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 one by one counts set bits [OK]
- Counting total digits instead of set bits
- Shifting bits without counting
- Counting zeros instead of ones
Solution
Step 1: Identify the correct bit clearing operation
The Brian Kernighan algorithm uses n = n & (n - 1) to clear the least significant set bit.Step 2: Verify the loop and count increment
Loop runs while n > 0 and increments count each time a bit is cleared.Final Answer:
int count = 0; while(n > 0) { n = n & (n - 1); count++; } -> Option CQuick Check:
Use n = n & (n - 1) to clear bits [OK]
- Using right shift instead of bit clearing
- Using bitwise OR instead of AND
- Counting bits by checking each bit manually
int n = 13; // binary 1101
int count = 0;
while (n > 0) {
n = n & (n - 1);
count++;
}
System.out.println(count);Solution
Step 1: Convert 13 to binary and count set bits
13 in binary is 1101, which has three set bits (1,1,0,1).Step 2: Apply Brian Kernighan algorithm iterations
Each iteration clears one set bit: - Iteration 1: 1101 & 1100 = 1100 - Iteration 2: 1100 & 1011 = 1000 - Iteration 3: 1000 & 0111 = 0000 Loop runs 3 times, so count = 3.Final Answer:
3 -> Option BQuick Check:
Number of set bits in 13 = 3 [OK]
- Counting total bits instead of set bits
- Miscounting set bits in binary
- Confusing bitwise AND with OR
int countSetBits(int n) {
int count = 0;
while (n != 0) {
n = n & (n + 1);
count++;
}
return count;
}Solution
Step 1: Check the bit clearing operation
The correct operation to clear the least significant set bit is n = n & (n - 1), not n & (n + 1).Step 2: Effect of incorrect operation
Using n + 1 does not clear the least significant set bit and leads to incorrect counting or infinite loop.Final Answer:
Using n + 1 instead of n - 1 in bit clearing step -> Option AQuick Check:
Use n & (n - 1) to clear bits [OK]
- Using n + 1 instead of n - 1
- Wrong loop condition causing infinite loop
- Confusing AND with OR operators
int totalSetBits(int[] arr) {
int total = 0;
for (int num : arr) {
while (num > 0) {
num = num & (num - 1);
total++;
}
}
return total;
}
What is the output of totalSetBits(new int[]{3, 5, 7})?Solution
Step 1: Count set bits for each element
3 (binary 11) has 2 set bits, 5 (binary 101) has 2 set bits, 7 (binary 111) has 3 set bits.Step 2: Sum all set bits
Total = 2 + 2 + 3 = 7.Step 3: Verify code logic
The code correctly counts set bits for each number and sums them in total.Final Answer:
7 -> Option AQuick Check:
Sum of set bits in 3,5,7 = 7 [OK]
- Miscounting set bits in numbers
- Adding counts incorrectly
- Using wrong bit clearing logic
Ready to prove it?
Pass the test and this pattern moves unknown
