Challenge - 5 Problems
Brian Kernighan Bit Master
Get all challenges correct to earn this badge!
Test your skills under time pressure!
❓ Predict Output
intermediateOutput of Brian Kernighan's Set Bits Count for 13
What is the output of the following Go code that counts set bits using Brian Kernighan's algorithm for the number 13?
DSA Go
package main import "fmt" func countSetBits(n int) int { count := 0 for n > 0 { n = n & (n - 1) count++ } return count } func main() { fmt.Println(countSetBits(13)) }
Attempts:
2 left
💡 Hint
Think about how many 1s are in the binary form of 13 (1101).
✗ Incorrect
The binary form of 13 is 1101, which has three 1s. Brian Kernighan's algorithm counts these by repeatedly turning off the rightmost set bit until the number becomes zero.
🧠 Conceptual
intermediateWhy does Brian Kernighan's Algorithm Work?
Why does the operation n = n & (n - 1) reduce the number of set bits by one in Brian Kernighan's algorithm?
Attempts:
2 left
💡 Hint
Consider what happens when you subtract 1 from a number in binary.
✗ Incorrect
Subtracting 1 flips the rightmost set bit and all bits to its right. ANDing with the original number clears that rightmost set bit, reducing the count by one.
❓ Predict Output
advancedCount Set Bits for 0 and 1 Using Brian Kernighan's Algorithm
What is the output of the following Go code when counting set bits for 0 and 1?
DSA Go
package main import "fmt" func countSetBits(n int) int { count := 0 for n > 0 { n = n & (n - 1) count++ } return count } func main() { fmt.Println(countSetBits(0)) fmt.Println(countSetBits(1)) }
Attempts:
2 left
💡 Hint
Remember that 0 has no set bits and 1 has exactly one set bit.
✗ Incorrect
0 has no bits set, so count is 0. 1 has one bit set, so count is 1.
🔧 Debug
advancedIdentify the Error in Brian Kernighan's Algorithm Implementation
What error will the following Go code produce when trying to count set bits using Brian Kernighan's algorithm?
DSA Go
package main import "fmt" func countSetBits(n int) int { count := 0 for n >= 0 { n = n & (n - 1) count++ } return count } func main() { fmt.Println(countSetBits(5)) }
Attempts:
2 left
💡 Hint
Check the loop condition and what happens when n becomes zero.
✗ Incorrect
The loop condition n >= 0 never becomes false for signed integers because when n reaches 0, n & (n-1) becomes 0 & -1 which is 0, so n stays 0 and the loop never ends.
🧠 Conceptual
expertTime Complexity of Brian Kernighan's Algorithm
What is the time complexity of Brian Kernighan's algorithm for counting set bits in an integer n?
Attempts:
2 left
💡 Hint
The loop runs once for each set bit.
✗ Incorrect
Brian Kernighan's algorithm runs in time proportional to the number of set bits because each iteration clears one set bit.
