Minimum Flips to Make a OR b Equal to c - Problem
Given three positive integers a, b, and c, find the minimum number of bit flips required to make the bitwise OR of a and b equal to c.
A flip operation consists of changing a single bit from 1 to 0 or from 0 to 1 in the binary representation of either a or b.
Goal: Transform a and b such that (a OR b) == c using the fewest possible bit flips.
Example: If a = 2 (binary: 10), b = 6 (binary: 110), and c = 5 (binary: 101), then a OR b = 110 (which is 6). To make it equal 5 (binary: 101), we need to flip specific bits in a or b.
Input & Output
example_1.py โ Basic Case
$
Input:
a = 2, b = 6, c = 5
โบ
Output:
3
๐ก Note:
a = 2 (010), b = 6 (110), c = 5 (101). Currently a OR b = 110 (6). To get 101 (5): Position 0: need 1, have 0 โ flip 1 bit. Position 1: need 0, have 1 (both a,b are 1) โ flip 2 bits. Position 2: need 1, have 1 โ no flips. Total: 1 + 2 + 0 = 3 flips.
example_2.py โ No Flips Needed
$
Input:
a = 4, b = 2, c = 6
โบ
Output:
0
๐ก Note:
a = 4 (100), b = 2 (010), c = 6 (110). Currently a OR b = 110 (6), which equals c = 6. No flips needed.
example_3.py โ Single Bit Numbers
$
Input:
a = 1, b = 2, c = 3
โบ
Output:
0
๐ก Note:
a = 1 (01), b = 2 (10), c = 3 (11). Currently a OR b = 11 (3), which equals c = 3. No flips needed.
Visualization
Tap to expand
Understanding the Visualization
1
Setup
You have two control panels (a and b) and a target pattern (c)
2
OR Logic
Each light is ON if either switch A OR switch B is ON for that position
3
Compare
Check each light position: does current state match target?
4
Flip Strategy
If target is ON but current is OFF: flip one switch. If target is OFF but current is ON: flip all ON switches
5
Sum
Count total switch flips across all positions
Key Takeaway
๐ฏ Key Insight: Each bit position can be analyzed independently. The minimum flips for each position depends on the current OR result and target bit: flip one bit to turn ON a position, flip all ON bits to turn OFF a position.
Time & Space Complexity
Time Complexity
O(log max(a,b,c))
We iterate through each bit position, and the maximum number of bits is log of the largest number
โก Linearithmic
Space Complexity
O(1)
Only using constant extra space for bit manipulation operations
โ Linear Space
Constraints
- 1 โค a, b, c โค 109
- All numbers are positive integers
- The maximum number of bits to consider is 32 (since numbers โค 109)
๐ก
Explanation
AI Ready
๐ก Suggestion
Tab
to accept
Esc
to dismiss
// Output will appear here after running code