PPractick

DSA interview question

Count the Number of Set Bits

Easy · Algorithms · Topics: bit manipulation

The problem

A feature-flag service stores which of 32 experiments a user is enrolled in as bits of an integer, and analytics dashboards constantly ask "how many experiments is this user in?", meaning how many bits are set. Checking all 32 bits one at a time works. Brian Kernighan's trick is neater: n & (n − 1) clears the lowest set bit, so repeating it until n is 0 takes exactly as many steps as there are set bits.

Example: 6 (110) → 2; 255 → 8.

Function signature

int countSetBits(int n);  // counts 1s in the 32-bit two's complement representation

Test cases

InputOutputExplanation
62110
811000
00
255811111111
214748364731INT_MAX
-132All 32 bits are set

(Confirm: negatives are counted in 32-bit two's complement.)

How interviewers phrase it

Clarifying questions to ask

  1. Signed or unsigned input? How should negatives be counted?
  2. Is this called once or many times? (Many calls may justify a lookup table.)
  3. Can I use built-ins like __builtin_popcount?

Follow-ups to expect

  1. "Why does Kernighan's loop work?"
  2. "Simple alternative?"
  3. "Faster for many queries?"
  4. "Counting bits for 0..n?"
  5. "Complexity?"

Practise questions like this with a real engineer

On Practick another engineer interviews you live for 60 minutes on a question from this bank. They have the full interviewer guide beside the call: the expected answer to every follow-up, hints to give if you stall, and a scoring rubric. You get the model solution once the session settles. It is free: interview someone for an hour and you have earned your own.

Book a free mock interview

Related questions

All 474 dsa interview questions

DSA mock interviews · System design interview questions · Free mock interview practice · Browse interviewers · Sign in