Minimum Flips to Make a OR b Equal to c

Easy Bit Manipulation

Problem

Given three integers a, b, and c, return the minimum number of bit flips required in a and b to make (a OR b) equal to c.

  • 0 ≤ a, b, c ≤ 10⁹

Example

Input: a = 2, b = 6, c = 5
Output: 3

Representing the numbers in binary: a = 010, b = 110, c = 101. The OR of a and b is 110, which differs from c in bits 0 and 2. To fix bit 0, flip b's bit from 1 to 0 (1 flip). For bit 1, no flip needed since OR is 1 and c's bit is 0, so flip both a and b bits from 1 to 0 (2 flips). Total flips = 3. The algorithm iterates through each bit position, compares bits of a, b, and c, and counts the flips needed accordingly.

Approach

Straightforward Solution

A brute-force approach might convert a, b, and c to binary strings, pad them, and compare bit by bit, counting flips. This is inefficient and cumbersome.

Core Observation

The OR operation on bits yields 1 if either bit is 1, and 0 only if both bits are 0. To make (a OR b) equal to c at each bit, flips are needed only when the current OR bit differs from c's bit.

Path to Optimal

The key insight is to use bitwise operations to extract the least significant bit of a, b, and c in each iteration, compare them, and count flips directly without string conversion. This approach leverages the properties of OR and bit manipulation to efficiently determine the minimal flips per bit.

Optimal Approach

Iterate while any of a, b, or c has bits left. Extract the least significant bit of each. If c's bit is 0, flips equal the sum of a's and b's bits (both must be flipped to 0). If c's bit is 1, flips equal 1 only if both a's and b's bits are 0 (one flip to set either bit to 1). Right shift a, b, and c to process the next bit. Sum all flips and return the total.

Time

O(log(max(a, b, c)))

The algorithm iterates once per bit of the largest input number, which is at most 31 bits for 32-bit integers, resulting in logarithmic time complexity.

Space

O(1)

Only a fixed number of integer variables are used for counting and bit extraction, with no additional data structures proportional to input size.

Pattern Spotlight

Bit Manipulation (Bitwise Iteration and Conditional Flip Counting)

When adjusting bits to satisfy a bitwise condition like OR, analyze each bit independently using bitwise AND and shifts, and count flips based on the minimal changes needed to achieve the target bit.

Solution

1class Solution:
2 def minFlips(self, a: int, b: int, c: int) -> int:
3 flips = 0
4
5 while a or b or c:
6 bit_a = a & 1
7 bit_b = b & 1
8 bit_c = c & 1
9
10 if bit_c == 0:
11 flips += bit_a + bit_b
12 elif bit_a == 0 and bit_b == 0:
13 flips += 1
14
15 a >>= 1
16 b >>= 1
17 c >>= 1
18
19 return flips

Step-by-Step Solution

1

Initialize Flip Counter to Accumulate Required Bit Flips

3flips = 0

Objective

To set up a counter variable that will accumulate the total number of bit flips needed.

Key Insight

A single integer variable is sufficient to track the cumulative flips as the algorithm processes each bit independently. This avoids complex data structures and keeps the solution efficient and straightforward.

Interview Quick-Check

Core Logic

Initializing a flips counter is essential to aggregate the minimal flips required across all bits.

Common Pitfalls & Bugs

Forgetting to initialize the counter or resetting it inside the loop would lead to incorrect total flips.

2

Iterate Through Bits of a, b, and c to Compare and Count Flips

5while a or b or c:
6 bit_a = a & 1
7 bit_b = b & 1
8 bit_c = c & 1
10 if bit_c == 0:
11 flips += bit_a + bit_b
12 elif bit_a == 0 and bit_b == 0:
13 flips += 1
15 a >>= 1
16 b >>= 1
17 c >>= 1

Objective

To examine each bit of a, b, and c, determine the flips needed to make (a OR b) equal to c at that bit, and accumulate the count.

Key Insight

By extracting the least significant bit of each integer using bitwise AND with 1, the algorithm isolates the current bit for comparison. The logic distinguishes two cases: if c's bit is 0, both a's and b's bits must be flipped to 0, so flips equal the sum of those bits; if c's bit is 1, flips are needed only if both a's and b's bits are 0, requiring one flip to set either bit to 1. Right shifting each integer moves to the next bit, enabling a loop that processes all bits efficiently.

Interview Quick-Check

Core Logic

The algorithm uses bitwise AND to extract bits and right shifts to progress through bits, applying conditional logic to count minimal flips per bit.

State & Boundaries

The loop continues while any of a, b, or c has remaining bits, ensuring all relevant bits are processed.

Common Pitfalls & Bugs

Incorrectly handling the case when c's bit is 1 can lead to overcounting flips; only one flip is needed if both bits are zero.

Complexity

Bitwise operations are constant time, so the loop runs in O(log n) time where n is the maximum of a, b, and c.

3

Return the Total Number of Flips After Processing All Bits

19return flips

Objective

To output the accumulated count of flips required to satisfy the condition (a OR b) == c.

Key Insight

Returning the flips counter after the loop completes provides the minimal number of bit flips needed. This final step concludes the algorithm by delivering the computed result.

Interview Quick-Check

Core Logic

Returning the flips variable gives the final answer after all bits have been processed.

Line Analysis

This solution has 4 Critical lines interviewers watch for.

Line 10 Critical
if bit_c == 0:

Check if c's current bit is 0.

If c's bit is 0, both a's and b's bits must be flipped to 0 to satisfy (a OR b) == c at this bit.

Line 11 Critical
flips += bit_a + bit_b

Add the sum of a's and b's bits to flips when c's bit is 0.

Each bit set to 1 in a or b must be flipped to 0, so the sum of these bits equals the flips needed for this case.

Line 12 Critical
elif bit_a == 0 and bit_b == 0:

Check if c's bit is 1 and both a's and b's bits are 0.

If c's bit is 1 but both a and b have 0 bits, one flip is needed to set either a or b's bit to 1 to satisfy the OR condition.

Line 13 Critical
flips += 1

Increment flips by 1 when both a and b bits are 0 but c's bit is 1.

This single flip changes one bit from 0 to 1, ensuring the OR matches c's bit without unnecessary flips.

Line 3 Core
flips = 0

Initialize a counter to track the total number of bit flips required.

This variable accumulates the minimal flips needed across all bits, serving as the core accumulator for the solution.

Line 6 Core
bit_a = a & 1

Extract the least significant bit of a.

Bitwise AND with 1 isolates the current bit of a, enabling per-bit comparison without string conversion.

Line 7 Core
bit_b = b & 1

Extract the least significant bit of b.

Similarly, isolating b's current bit allows direct comparison with a and c bits.

Line 8 Core
bit_c = c & 1

Extract the least significant bit of c.

Isolating c's bit is essential to determine the target bit value for the OR operation at this position.

Line 19 Core
return flips

Return the total number of flips required.

After processing all bits, this returns the minimal flips needed to make (a OR b) equal to c.

Line 5 Core
while a or b or c:

Continue looping while any bits remain in a, b, or c.

This condition ensures all bits of the inputs are processed, including leading zeros, until no bits remain to compare.

Line 15 Core
a >>= 1

Right shift a to process the next bit.

Shifting a right by one bit moves the next bit into the least significant position for the next iteration.

Line 16 Core
b >>= 1

Right shift b to process the next bit.

Similarly, shifting b prepares the next bit for comparison in the following loop iteration.

Line 17 Core
c >>= 1

Right shift c to process the next bit.

Shifting c aligns the next target bit for the OR comparison in the next iteration.

Test Your Understanding

Why does the algorithm only need to examine bits until all of a, b, and c become zero?

Because once all bits of a, b, and c are zero, no further flips are needed; higher bits are zero by default and do not affect the OR result.

Related Problems

Bit Manipulation pattern

Don't just read it. Drill it.

Reconstruct Minimum Flips to Make a OR b Equal to c from memory until it sticks. AlgoDrill blanks out key lines and makes you fill them back in, step by step.

Unlock the Minimum Flips to Make a OR b Equal to c drill

or drill a free problem