1318. Minimum Flips to Make a OR b Equal to c
Problem Description
You are given three positive integers a
, b
, and c
. Your task is to find the minimum number of bit flips needed in a
and b
to make the result of (a OR b)
equal to c
.
A bit flip operation means changing a single bit from 1
to 0
or from 0
to 1
in the binary representation of a number.
The bitwise OR operation works by comparing corresponding bits of two numbers. For each bit position, if at least one of the bits is 1
, the result bit is 1
. If both bits are 0
, the result bit is 0
.
To solve this problem, you need to examine each bit position in the binary representations of a
, b
, and c
. For each bit position i
:
- Extract the
i-th
bit froma
,b
, andc
(let's call themx
,y
, andz
) - If
z
is0
, then bothx
andy
must be0
to satisfy(x OR y) = z
. Count how many flips are needed (ifx
is1
, flip it; ify
is1
, flip it) - If
z
is1
, then at least one ofx
ory
must be1
. If both are0
, you only need to flip one of them
The solution iterates through 32 bits (covering the range of typical integers) and accumulates the total number of flips required. When the target bit z
is 0
, the number of flips needed is x + y
(since both must become 0
). When z
is 1
, we need one flip only if both x
and y
are currently 0
.
Intuition
The key insight is that we need to examine the problem bit by bit. Since the OR operation works independently on each bit position, we can solve the problem by checking each bit position separately and counting the minimum flips needed at each position.
For any bit position, there are only a few possible scenarios:
-
If the target bit
c[i]
is1
, we need at least one ofa[i]
orb[i]
to be1
. If both are already0
, we only need to flip one of them (minimum cost = 1). -
If the target bit
c[i]
is0
, we need botha[i]
andb[i]
to be0
(since0 OR 0 = 0
). If either or both are1
, we must flip them all to0
.
This leads us to a simple counting strategy:
- When we need the result to be
0
: Count how many1
s we have in positionsa[i]
andb[i]
. Each1
needs to be flipped to0
. - When we need the result to be
1
: Check if we already have at least one1
. If not (both are0
), we need exactly one flip.
The beauty of this approach is that each bit position is independent, so we can simply iterate through all 32 bits, apply our counting logic at each position, and sum up the total flips needed. This gives us an efficient O(32)
= O(1)
solution in terms of the number of bits we need to check.
Solution Approach
The implementation uses bit manipulation to extract and compare individual bits from the three numbers. Here's how the algorithm works:
-
Initialize a counter: Start with
ans = 0
to track the total number of flips needed. -
Iterate through each bit position: Loop through 32 bits (from position 0 to 31) to cover the entire range of a standard integer.
-
Extract individual bits: For each bit position
i
:- Extract the
i-th
bit froma
:x = a >> i & 1
- Extract the
i-th
bit fromb
:y = b >> i & 1
- Extract the
i-th
bit fromc
:z = c >> i & 1
The expression
num >> i & 1
right-shifts the number byi
positions and then masks with1
to get only the least significant bit. - Extract the
-
Count flips based on the target bit:
- If
z == 0
: We need bothx
andy
to be0
. The number of flips required isx + y
because:- If
x = 1
, we need 1 flip to make it0
- If
y = 1
, we need 1 flip to make it0
- If both are
1
, we need 2 flips total
- If
- If
z == 1
: We need at least one ofx
ory
to be1
. We only need to flip if both are0
:int(x == 0 and y == 0)
returns1
if both are0
(need one flip), otherwise0
- If
-
Accumulate the result: Add the flips needed for the current bit position to
ans
. -
Return the total: After checking all 32 bits, return the accumulated count.
The time complexity is O(1)
since we always check exactly 32 bits, and the space complexity is O(1)
as we only use a few variables regardless of input size.
Ready to land your dream job?
Unlock your dream job with a 5-minute evaluator for a personalized learning plan!
Start EvaluatorExample Walkthrough
Let's walk through a concrete example with a = 2
, b = 6
, and c = 5
.
First, let's look at the binary representations:
a = 2
→010
in binaryb = 6
→110
in binaryc = 5
→101
in binary (our target)
Currently, a OR b = 010 OR 110 = 110
(which is 6), but we need it to equal 101
(which is 5).
Now let's examine each bit position from right to left (positions 0, 1, 2):
Bit position 0 (rightmost bit):
a[0] = 0
,b[0] = 0
,c[0] = 1
- Current:
0 OR 0 = 0
, but we need1
- Since both
a[0]
andb[0]
are0
, we need to flip one of them to1
- Flips needed: 1
Bit position 1 (middle bit):
a[1] = 1
,b[1] = 1
,c[1] = 0
- Current:
1 OR 1 = 1
, but we need0
- To get
0
, both bits must be0
, so we need to flip botha[1]
andb[1]
- Flips needed: 2
Bit position 2 (leftmost bit):
a[2] = 0
,b[2] = 1
,c[2] = 1
- Current:
0 OR 1 = 1
, which matches what we need - No flips needed: 0
Total flips = 1 + 2 + 0 = 3
After making these 3 flips:
- We could flip
a[0]
from0
to1
, makinga = 011
(3 in decimal) - We flip
a[1]
from1
to0
andb[1]
from1
to0
, makingb = 100
(4 in decimal) - Now
a OR b = 011 OR 100 = 111
... wait, that's not right!
Let me recalculate. After the flips:
- If we flip
b[0]
from0
to1
:b
becomes111
- If we flip
a[1]
from1
to0
:a
becomes000
- If we flip
b[1]
from1
to0
:b
becomes101
- Final:
a = 000
,b = 101
, soa OR b = 000 OR 101 = 101 = 5
✓
This matches our target c = 5
with exactly 3 bit flips.
Solution Implementation
1class Solution:
2 def minFlips(self, a: int, b: int, c: int) -> int:
3 """
4 Calculate minimum bit flips needed to make (a OR b) == c.
5
6 Args:
7 a: First integer
8 b: Second integer
9 c: Target integer result of (a OR b)
10
11 Returns:
12 Minimum number of bit flips required
13 """
14 flip_count = 0
15
16 # Check each bit position (32-bit integers)
17 for bit_position in range(32):
18 # Extract the i-th bit from each number
19 bit_a = (a >> bit_position) & 1
20 bit_b = (b >> bit_position) & 1
21 bit_c = (c >> bit_position) & 1
22
23 # Calculate flips needed for current bit position
24 if bit_c == 0:
25 # If target bit is 0, both a and b bits must be 0
26 # Count how many 1s need to be flipped to 0
27 flip_count += bit_a + bit_b
28 else:
29 # If target bit is 1, at least one of a or b must be 1
30 # Only flip if both are 0
31 flip_count += int(bit_a == 0 and bit_b == 0)
32
33 return flip_count
34
1class Solution {
2 public int minFlips(int a, int b, int c) {
3 int flipCount = 0;
4
5 // Check each bit position (0 to 31 for 32-bit integers)
6 for (int bitPosition = 0; bitPosition < 32; bitPosition++) {
7 // Extract the bit at current position for each number
8 int bitA = (a >> bitPosition) & 1;
9 int bitB = (b >> bitPosition) & 1;
10 int bitC = (c >> bitPosition) & 1;
11
12 // Calculate flips needed for current bit position
13 if (bitC == 0) {
14 // If target bit is 0, both a and b bits must be 0
15 // Need to flip all 1s to 0s
16 flipCount += bitA + bitB;
17 } else {
18 // If target bit is 1, at least one of a or b must be 1
19 // Only need to flip if both are 0
20 if (bitA == 0 && bitB == 0) {
21 flipCount += 1;
22 }
23 }
24 }
25
26 return flipCount;
27 }
28}
29
1class Solution {
2public:
3 int minFlips(int a, int b, int c) {
4 int flipsCount = 0;
5
6 // Check each bit position (0 to 31 for 32-bit integers)
7 for (int bitPosition = 0; bitPosition < 32; ++bitPosition) {
8 // Extract the i-th bit from each number
9 int bitA = (a >> bitPosition) & 1;
10 int bitB = (b >> bitPosition) & 1;
11 int bitC = (c >> bitPosition) & 1;
12
13 // Calculate flips needed for current bit position
14 if (bitC == 0) {
15 // If target bit is 0, both a and b bits must be 0
16 // Need to flip all 1s to 0s
17 flipsCount += bitA + bitB;
18 } else {
19 // If target bit is 1, at least one of a or b bits must be 1
20 // Only need to flip if both are 0
21 if (bitA == 0 && bitB == 0) {
22 flipsCount += 1;
23 }
24 }
25 }
26
27 return flipsCount;
28 }
29};
30
1/**
2 * Calculates the minimum number of bit flips needed to make (a | b) == c
3 * @param a - First integer operand for OR operation
4 * @param b - Second integer operand for OR operation
5 * @param c - Target result of (a | b) after flips
6 * @returns Minimum number of bit flips required
7 */
8function minFlips(a: number, b: number, c: number): number {
9 let flipsCount: number = 0;
10
11 // Check each bit position (32-bit integers)
12 for (let bitPosition: number = 0; bitPosition < 32; bitPosition++) {
13 // Extract the bit at current position for each number
14 const bitA: number = (a >> bitPosition) & 1;
15 const bitB: number = (b >> bitPosition) & 1;
16 const bitC: number = (c >> bitPosition) & 1;
17
18 // Calculate flips needed for current bit position
19 if (bitC === 0) {
20 // When target bit is 0, both a and b bits must be 0
21 // Need to flip all 1s to 0s
22 flipsCount += bitA + bitB;
23 } else {
24 // When target bit is 1, at least one of a or b must be 1
25 // If both are 0, need to flip one of them to 1
26 flipsCount += (bitA + bitB === 0) ? 1 : 0;
27 }
28 }
29
30 return flipsCount;
31}
32
Time and Space Complexity
The time complexity is O(log M)
, where M
is the maximum value among the numbers a
, b
, and c
. Since the loop iterates exactly 32 times (checking each bit position in a 32-bit integer), this can also be expressed as O(32) = O(1)
. However, in a more general sense where we consider arbitrary precision integers, the complexity would be O(log M)
as we need to check each bit position up to the most significant bit.
The space complexity is O(1)
as the algorithm only uses a constant amount of extra space. The variables ans
, i
, x
, y
, and z
are the only additional storage used, regardless of the input size.
Learn more about how to find time and space complexity quickly.
Common Pitfalls
1. Incorrect Handling When Target Bit is 0
A common mistake is thinking that when the target bit c
is 0, you only need to flip one bit even if both a
and b
have 1s at that position. This is wrong because the OR operation requires BOTH bits to be 0 to produce a 0.
Incorrect approach:
if bit_c == 0: # WRONG: Only counting one flip maximum flip_count += 1 if (bit_a == 1 or bit_b == 1) else 0
Correct approach:
if bit_c == 0: # RIGHT: Both bits must be 0, so count each 1 that needs flipping flip_count += bit_a + bit_b
2. Not Considering the Full Bit Range
Another pitfall is iterating through fewer than 32 bits, which might miss significant bits in larger numbers. While Python handles arbitrary precision integers, the problem typically assumes 32-bit integers.
Incorrect approach:
# WRONG: May miss bits if numbers are large while a > 0 or b > 0 or c > 0: bit_a = a & 1 bit_b = b & 1 bit_c = c & 1 # ... process bits a >>= 1 b >>= 1 c >>= 1
Correct approach:
# RIGHT: Always check all 32 bits
for bit_position in range(32):
bit_a = (a >> bit_position) & 1
bit_b = (b >> bit_position) & 1
bit_c = (c >> bit_position) & 1
# ... process bits
3. Misunderstanding the OR Operation Logic
Some might incorrectly think that when the target bit is 1, you need to make both a
and b
equal to 1. This wastes flips since OR only requires at least one bit to be 1.
Incorrect approach:
if bit_c == 1: # WRONG: Making both bits 1 when only one is needed flip_count += (1 - bit_a) + (1 - bit_b)
Correct approach:
if bit_c == 1:
# RIGHT: Only flip if both are 0 (need exactly one flip)
flip_count += int(bit_a == 0 and bit_b == 0)
Complete Solution with Pitfall Avoidance:
class Solution:
def minFlips(self, a: int, b: int, c: int) -> int:
flip_count = 0
# Always iterate through all 32 bits
for i in range(32):
bit_a = (a >> i) & 1
bit_b = (b >> i) & 1
bit_c = (c >> i) & 1
if bit_c == 0:
# Both must be 0 - count all 1s that need flipping
flip_count += bit_a + bit_b
else:
# At least one must be 1 - only flip if both are 0
flip_count += 1 if (bit_a == 0 and bit_b == 0) else 0
return flip_count
What is an advantages of top-down dynamic programming vs bottom-up dynamic programming?
Recommended Readings
Coding Interview Patterns Your Personal Dijkstra's Algorithm to Landing Your Dream Job The goal of AlgoMonster is to help you get a job in the shortest amount of time possible in a data driven way We compiled datasets of tech interview problems and broke them down by patterns This way
Recursion Recursion is one of the most important concepts in computer science Simply speaking recursion is the process of a function calling itself Using a real life analogy imagine a scenario where you invite your friends to lunch https assets algo monster recursion jpg You first call Ben and ask
Runtime Overview When learning about algorithms and data structures you'll frequently encounter the term time complexity This concept is fundamental in computer science and offers insights into how long an algorithm takes to complete given a certain input size What is Time Complexity Time complexity represents the amount of time
Want a Structured Path to Master System Design Too? Don’t Miss This!