Python 1318.py
class Solution:
def minFlips(self, a: int, b: int, c: int) -> int:
result = 0
while a > 0 or b > 0 or c > 0:
if c & 1:
result += 1 - ((a | b) & 1)
else:
result += a & 1
result += b & 1
a >>= 1
b >>= 1
c >>= 1
return result
Difficulty
and has an acceptance rate of about 72% (200k+ submissions).
Typical patterns to solve this problem:
- Bit Manipulation
AI Disclaimer
However, two years later I set up this website and used various AI tools to generate most of the walkthrough / explanations below.
See this dedicated page for more details.
Code Walkthrough
Overview
The provided Solution class implements a method minFlips that computes the minimum number of bit flips required to make the bitwise OR of two integers a and b equal to a third integer c. The algorithm processes the three numbers bit by bit, from the least-significant position upward, accumulating the required flips in the variable result. The loop terminates when all three numbers have been fully shifted out, guaranteeing that every relevant bit has been examined.
Bitwise Traversal Loop
while a > 0 or b > 0 or c > 0:
...
a >>= 1
b >>= 1
c >>= 1
The core of the solution is a while loop that continues as long as any of the three integers still contains set bits. Inside the loop the current least-significant bits of a, b, and c are examined. After the necessary calculations, each integer is right-shifted by one position (>>= 1), effectively moving to the next higher bit for the subsequent iteration. This design ensures that the algorithm adapts to inputs of varying bit lengths without requiring explicit length calculations.
Handling When the Target Bit Is 1
if c & 1:
result += 1 - ((a | b) & 1)
When the current bit of c is 1, the desired outcome of a | b at that position must also be 1. The expression (a | b) & 1 extracts the resulting bit of the OR operation for the current position. If this bit is already 1, the subtraction yields 0, meaning no flip is needed. If the OR result is 0, the subtraction yields 1, indicating that exactly one flip (either in a or b) is required to turn the OR result to 1. This concise arithmetic captures the conditional increment without branching.
Handling When the Target Bit Is 0
else:
result += a & 1
result += b & 1
When the current bit of c is 0, the OR of a and b must also be 0. Consequently, both a and b must have a 0 at this position. The code adds the value of the least-significant bit of a (a & 1) and the least-significant bit of b (b & 1) directly to result. Each addition contributes 1 only when the corresponding bit is 1, reflecting the need to flip that bit to 0. This handles the case where both bits may need to be cleared independently.
Loop Termination
The loop condition a > 0 or b > 0 or c > 0 guarantees termination because each iteration right-shifts the three integers, steadily reducing their magnitude. Once all three numbers become zero, the condition fails and the loop exits. At that point, result holds the total number of flips required across all processed bits.
Edge Cases Handled
The algorithm naturally accommodates inputs where any of the numbers is zero. If a or b is zero, the corresponding bit extraction (a & 1 or b & 1) yields 0, and the shift operation leaves the value unchanged at zero, so no extra work is performed. When c is zero, the else branch is always taken, and the method correctly counts flips needed to clear any set bits in a or b. The loop also correctly processes cases where the numbers have different bit lengths; the shift-based termination ensures that trailing zeros in shorter numbers do not affect the result.
Performance Optimizations
The implementation relies exclusively on bitwise operators (&, |, >>) and integer arithmetic, which are executed in constant time at the CPU level. By avoiding any conversion to binary strings or auxiliary data structures, the method minimizes memory overhead and leverages the processor’s native bit manipulation capabilities. The use of a single accumulator variable (result) eliminates the need for intermediate collections, further reducing allocation pressure. The arithmetic expression 1 - ((a | b) & 1) replaces a conditional branch with a simple subtraction, which can improve pipeline predictability on modern CPUs. Overall, the design achieves a tight, low-level loop that processes each bit exactly once.
ELI5 - Simplified Explanation
Imagine you have three boxes of light switches. Each box contains a long row of switches that can be either on or off. The code looks at these three boxes one switch at a time, moving from the very last switch all the way to the first one.
For every position, the goal is to make the switches in the first two boxes match the switch in the third box. The code checks if the switch in the third box is flipped on. If it is, the code makes sure that at least one of the switches in the first two boxes is also on. If neither of them is on, it counts a flip to turn one of them on.
If the switch in the third box is flipped off, the code makes sure both switches in the first two boxes are also off. If any of those are currently on, it counts a flip to turn them off.
After checking a spot, the code slides over to look at the next switch by shifting everything down the line. This keeps happening until all the switches in all three boxes have been checked. The final count represents the total number of flips needed to make the boxes match up perfectly.
Code Quality
Complexity Analysis
Other Solutions
Obviously, I did that after I solved the problem myself.
In general, AlgoMonster and WalkCCC solutions are high-quality and always worth a look.
I haven't checked most of the other solutions, but they might be helpful as well.
And of course, the LeetCode forum is always a good place (or even the best) to look for alternative approaches.
(click on a column header to sort the table)
| author | ||||||||
|---|---|---|---|---|---|---|---|---|
| author | solutions | |||||||
| www | AlgoMonster | C++ | Java | Python | TS | |||
| WalkCCC | C++ | Java | Python | |||||
| leetcode.ca | C++ | Java | Python | Go | TS | |||
| Progiez | C++ | Java | Python | |||||
| github | BigEggStudy | C# | ||||||
| black-shadows | C++ | |||||||
| charles-wangkai | Java | |||||||
| fpdjsns | C++ | |||||||
| fsq | C++ | |||||||
| JoshCrozier | JS | |||||||
| keineahnung2345 | C++ | |||||||
| lkwq007 | Python | |||||||
| suxrobGM | C# | |||||||
| varunu28 | Java | |||||||
| AlgoMonster | C++, Python, Java, TypeScript | |||||||
| WalkCCC | C++, Python, Java | |||||||
| leetcode.ca | C++, Go, Java, Python, TypeScript | |||||||
| Progiez | C++, Java, Python | |||||||
| BigEggStudy | C# | |||||||
| black-shadows | C++, C++ | |||||||
| charles-wangkai | Java | |||||||
| fpdjsns | C++ | |||||||
| fsq | C++ | |||||||
| JoshCrozier | JavaScript | |||||||
| keineahnung2345 | C++ | |||||||
| lkwq007 | Python | |||||||
| suxrobGM | C# | |||||||
| varunu28 | Java |
Videos
Similar Problems
- problem 2220: Minimum Bit Flips to Convert Number
Solved On The Same Day
- problem 643: Maximum Average Subarray I
- problem 1431: Kids With the Greatest Number of Candies
- problem 310: Minimum Height Trees
- problem 334: Increasing Triplet Subsequence
- problem 355: Design Twitter
- problem 368: Largest Divisible Subset
- problem 382: Linked List Random Node
- problem 398: Random Pick Index
- problem 1004: Max Consecutive Ones III
- problem 1679: Max Number of K-Sum Pairs
Extra
- Tech Stack - my development environment and tools
- AI - how AI helped me create this website (NOT solving the problems)
- Progress - progression over time
- Quality - code quality