Bird
Raised Fist0
DSA Typescriptprogramming

Count Set Bits Brian Kernighan Algorithm in DSA Typescript

Choose your learning style10 modes available
Mental Model
Count how many 1s are in a number's binary form by removing the rightmost 1 bit one by one.
Analogy: Imagine you have a row of lit candles (1s). Each time you blow out the rightmost lit candle, you count one until none are left.
Number: 13 (binary 1101)
Bits: 1 -> 1 -> 0 -> 1
Rightmost 1 bit marked: 1 -> 1 -> 0 -> [1] ↑
Dry Run Walkthrough
Input: number = 13 (binary 1101)
Goal: Count how many bits are set to 1 in the binary form of 13
Step 1: Remove rightmost set bit from 1101 (13)
1101 (13) -> 1100 (12)
Why: Removing rightmost 1 reduces count by one, helps count total set bits
Step 2: Remove rightmost set bit from 1100 (12)
1100 (12) -> 1000 (8)
Why: Next rightmost 1 removed to count another set bit
Step 3: Remove rightmost set bit from 1000 (8)
1000 (8) -> 0000 (0)
Why: Last set bit removed, counting complete
Result:
0000 (0) -> total set bits counted = 3
Annotated Code
DSA Typescript
class BitCounter {
  static countSetBits(n: number): number {
    let count = 0;
    while (n !== 0) {
      n = n & (n - 1); // remove rightmost set bit
      count++; // increment count for each removal
    }
    return count;
  }
}

// Driver code
const number = 13;
const result = BitCounter.countSetBits(number);
console.log(`Number of set bits in ${number} is ${result}`);
while (n !== 0) {
loop until all set bits are removed
n = n & (n - 1); // remove rightmost set bit
remove rightmost set bit to count it
count++; // increment count for each removal
count how many set bits removed
OutputSuccess
Number of set bits in 13 is 3
Complexity Analysis
Time: O(k) where k is number of set bits because each iteration removes one set bit
Space: O(1) because only a few variables are used regardless of input size
vs Alternative: Naive approach checks all bits (O(log n)), Brian Kernighan's method is faster when number has fewer set bits
Edge Cases
number = 0 (no set bits)
loop does not run, count remains 0
DSA Typescript
while (n !== 0) {
number = 1 (single set bit)
loop runs once, count becomes 1
DSA Typescript
while (n !== 0) {
number with all bits set (e.g., 7 for 3 bits)
loop runs for each set bit, counting all
DSA Typescript
while (n !== 0) {
When to Use This Pattern
When you need to count how many bits are 1 in a number efficiently, use Brian Kernighan's algorithm because it quickly removes one set bit per step.
Common Mistakes
Mistake: Using n & 1 and shifting right to count bits, which is slower
Fix: Use n = n & (n - 1) to remove rightmost set bit directly
Summary
Counts how many bits are set to 1 in a number using a fast bit removal trick.
Use when you want an efficient way to count set bits without checking every bit.
The key insight is that n & (n - 1) removes the rightmost set bit, letting you count bits quickly.

Practice

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

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 set bits were present.
  3. Final Answer:

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

    Clearing bits one by one counts set bits [OK]
Hint: Clear least set bit repeatedly to count set bits [OK]
Common Mistakes:
  • Confusing bit count with digit count
  • Using simple right shifts without bit checks
  • Ignoring bitwise AND operation
2. Which of the following is the correct TypeScript syntax to clear the least significant set bit of a number n?
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 bitwise operation to clear least set bit

    The operation n = n & (n - 1) clears the least significant set bit in n.
  2. Step 2: Verify other options

    OR, XOR, and addition do not clear the least significant set bit correctly.
  3. Final Answer:

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

    AND with (n-1) clears least set bit [OK]
Hint: Use AND with (n-1) to clear least set bit [OK]
Common Mistakes:
  • Using OR or XOR instead of AND
  • Adding numbers instead of bitwise operations
  • Missing parentheses around (n - 1)
3. What is the output of the following TypeScript code?
function countSetBits(n: number): number {
  let count = 0;
  while (n > 0) {
    n = n & (n - 1);
    count++;
  }
  return count;
}

console.log(countSetBits(13));
medium
A. 3
B. 4
C. 2
D. 5

Solution

  1. Step 1: Convert 13 to binary and count set bits

    13 in binary is 1101, which has three set bits (1,1,0,1).
  2. Step 2: Apply Brian Kernighan algorithm steps

    Each iteration clears one set bit, so count increments 3 times until n becomes 0.
  3. Final Answer:

    3 -> Option A
  4. Quick Check:

    Number of 1s in 1101 = 3 [OK]
Hint: Count 1s in binary using n & (n-1) loop [OK]
Common Mistakes:
  • Counting total bits instead of set bits
  • Misunderstanding binary representation
  • Off-by-one errors in loop count
4. Identify the error in this TypeScript function that tries to count set bits using Brian Kernighan's algorithm:
function countSetBits(n: number): number {
  let count = 0;
  while (n != 0) {
    n = n & n - 1;
    count++;
  }
  return count;
}
medium
A. Return statement is missing.
B. Using != instead of > in the while condition.
C. Incorrect initialization of count variable.
D. Missing parentheses around (n - 1) in the expression.

Solution

  1. Step 1: Analyze the expression inside the loop

    The expression n = n & n - 1 lacks parentheses, so it is evaluated as (n & n) - 1, which is incorrect.
  2. Step 2: Correct expression

    It should be n = n & (n - 1) to correctly clear the least significant set bit.
  3. Final Answer:

    Missing parentheses around (n - 1) in the expression. -> Option D
  4. Quick Check:

    Parentheses ensure correct order of operations [OK]
Hint: Use parentheses: n = n & (n - 1) [OK]
Common Mistakes:
  • Using != 0 causing potential infinite loop for negatives
  • Assuming both conditions always equivalent
  • Operator precedence confusion causing wrong calculation
5. Given an array of numbers [5, 7, 10], which TypeScript code correctly uses Brian Kernighan's algorithm to return an array of their set bit counts?
hard
A. const counts = arr.map(n => { let count = 0; while (n > 0) { n = n >> 1; count++; } return count; });
B. const counts = arr.map(n => n.toString(2).length);
C. const counts = arr.map(n => { let count = 0; while (n > 0) { n = n & (n - 1); count++; } return count; });
D. const counts = arr.map(n => { let count = 0; for (let i = 0; i < 32; i++) { if ((n & (1 << i)) !== 0) count++; } return count; });

Solution

  1. Step 1: Understand Brian Kernighan's algorithm usage

    const counts = arr.map(n => { let count = 0; while (n > 0) { n = n & (n - 1); count++; } return count; }); uses the correct loop with n = n & (n - 1) to count set bits for each number.
  2. Step 2: Check other options for correctness

    const counts = arr.map(n => n.toString(2).length); counts total binary digits, not set bits. const counts = arr.map(n => { let count = 0; while (n > 0) { n = n >> 1; count++; } return count; }); counts total bits by shifting, not set bits. const counts = arr.map(n => { let count = 0; for (let i = 0; i < 32; i++) { if ((n & (1 << i)) !== 0) count++; } return count; }); uses a loop checking each bit, which works but is not Brian Kernighan's algorithm.
  3. Final Answer:

    const counts = arr.map(n => { let count = 0; while (n > 0) { n = n & (n - 1); count++; } return count; }); -> Option C
  4. Quick Check:

    Use n & (n-1) loop inside map for set bits [OK]
Hint: Use map with n & (n-1) loop for each number [OK]
Common Mistakes:
  • Counting binary string length instead of set bits
  • Using right shift without bit check
  • Confusing bitwise loop with simple iteration
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