PPractick

DSA interview question

Minimum Bit Flips to Convert a Number

Medium · Algorithms · Topics: bit manipulation

The problem

A configuration register is currently set to start, and it must be changed to goal. The hardware can only flip one bit at a time, and each flip is slow, so the operator wants the minimum number of flips. Every bit where the two numbers differ must be flipped exactly once, and no other flips are needed. XOR marks exactly those differing positions with 1s, so the answer is the number of set bits in start ^ goal.

Example: start = 10 (1010), goal = 7 (0111) → 3.

Function signature

int minBitFlips(int start, int goal);  // 0 <= start, goal <= 10^9

Test cases

Input (start, goal)OutputExplanation
(10, 7)31010 ^ 0111 = 1101
(3, 4)3011 ^ 100 = 111
(0, 0)0
(0, 1023)10Ten 1 bits to create
(1000000000, 0)1310⁹ has 13 set bits

(Confirm: a flip changes one bit; any bit position may be flipped, including leading zeros.)

How interviewers phrase it

Clarifying questions to ask

  1. Can the numbers be negative? (Not in LeetCode's version.)
  2. Is a flip always one bit? (Yes.)
  3. Should leading zeros be considered? (Yes: any position may be flipped.)

Follow-ups to expect

  1. "Why is XOR the right tool?"
  2. "How do you count the 1s?"
  3. "Total Hamming distance over all pairs in an array?"
  4. "Why is this the minimum?"
  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