Minimum Flips to Make a OR b Equal to c — LeetCode 1318 Python Solution

MediumBit Manipulation
Problem
#1318
Reading time
2 min

The problem

Given 3 positives numbers a, b and c. Return the minimum flips required in some bits of a and b to make ( a OR b == c ).

Example

Input
a = 2, b = 6, c = 5
Output
3
Explanation
After flips a = 1 , b = 4 , c = 5 such that (a OR b == c)

Python solution

Python
class Solution:
    def minFlips(self, a: int, b: int, c: int) -> int:
        ans = 0
        for i in range(32):
            x, y, z = a >> i & 1, b >> i & 1, c >> i & 1
            ans += x + y if z == 0 else int(x == 0 and y == 0)
        return ans

Complexity

MeasureComplexity
TimeO(\log M), where M is the maximum value of the numbers in the problem
SpaceO(1) auxiliary

Pattern: Bit Manipulation

Use XOR, masks and the low-bit trick to replace whole data structures with an integer. LeetCode 1318. Minimum Flips to Make a OR b Equal to c is filed here on both counts: the reference solution below belongs to the algorithm family this hub collects, and LeetCode tags it Bit Manipulation.

The bit manipulation guide has the Python template for the pattern and the 194 LeetCode problems that use it.

Related problems

On a study list

This problem is on LeetCode 75.

Frequently asked questions

How hard is LeetCode 1318. Minimum Flips to Make a OR b Equal to c?
LeetCode 1318. Minimum Flips to Make a OR b Equal to c is rated Medium on LeetCode.
What is the time complexity of LeetCode 1318. Minimum Flips to Make a OR b Equal to c?
The Python solution on this page runs in O(\log M), where M is the maximum value of the numbers in the problem.
What is the space complexity of LeetCode 1318. Minimum Flips to Make a OR b Equal to c?
The Python solution on this page uses O(1) auxiliary space.
What topics does LeetCode 1318. Minimum Flips to Make a OR b Equal to c cover?
LeetCode 1318. Minimum Flips to Make a OR b Equal to c is tagged Bit Manipulation on LeetCode.

Stuck on problems like this in a live interview?

Stealth Interview is a desktop app for macOS and Windows. It reads the problem off your screen and returns a working solution with a step-by-step explanation and its time and space complexity — invisible to screen sharing.

Get Stealth Interview