Minimum Flips to Make a OR b Equal to c
Expert Answer & Key Takeaways
A complete guide to understanding and implementing Bit Manipulation.
Minimum Flips to Make a OR b Equal to c
Given 3 positives
a, b and c. Return the minimum flips required in some bits of a and b to make (a OR b == c).Examples
Input: a = 2, b = 6, c = 5
Output: 3
Input: a = 4, b = 2, c = 7
Output: 1
Approach 1
Level I: Brute Force (Bit-by-Bit Check)
Intuition
Iterate through each bit of the three numbers and compare the required state
c with the current state a | b. Count the flips needed for each bit position.Thought Process
- For each bit position (0 to 31):
- If -th bit of
cis 0:- Both -th bits of
aandbmust be 0. Add their sum toflips.
- Both -th bits of
- If -th bit of
cis 1:- At least one of -th bits of
aorbmust be 1. If both are 0, add 1 toflips.
- At least one of -th bits of
- If -th bit of
- Return
flips.
Pattern: Positional Verification
⏱ O(1) - Always 32 iterations.💾 O(1) - Constant space.
Approach 2
Level II: Iterative with Built-in Counting
Intuition
Instead of checking every bit manually, we can use built-in bit counting functions to calculate the flips needed for the entire numbers after identifying which bits are incorrect via XOR and AND.
⏱ $O(1)$💾 $O(1)$
Approach 3
Level III: Optimal (Bitwise Magic)
Intuition
We can use bitwise operators to find all differing bits at once.
(a | b) ^ c gives bits that are incorrect. We then handle the cases where c bit is 0 separately as they might require 2 flips per bit.Thought Process
incorrect = (a | b) ^ c.must_flip_two = a & b & incorrect.- Flips = Count of set bits in
incorrect+ Count of set bits inmust_flip_two.
Pattern: Composite Bitmasking
⏱ O(1) - Constant number of bitwise operations.💾 O(1) - Constant space.
Detailed Dry Run
a=2(0010), b=6(0110), c=5(0101)
a|b = 6 (0110)
incorrect = 0110 ^ 0101 = 0011 (bits 0 and 1 are wrong)
must_flip_two = 0010 & 0110 & 0011 = 0010 (bit 1 is wrong and both a,b are 1)
Total = popcount(0011) + popcount(0010) = 2 + 1 = 3.
Course4All Technical Board
Verified ExpertSenior Software Engineers & Algorithmic Experts
Our DSA content is authored and reviewed by engineers from top tech firms to ensure optimal time and space complexity analysis.
Pattern: 2026 Ready
Updated: Weekly
Found an issue or have a suggestion?
Help us improve! Report bugs or suggest new features on our Telegram group.