MediumNo. 1318

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

Topics
Bit Manipulation
On a study list
LeetCode 75
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

PythonSolution
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

Time
O(log M)where M is the maximum value of the numbers in the problem
Space · auxiliary
O(1)

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

Related problems
No.ProblemDifficulty
0029Divide Two IntegersMedium
0067Add BinaryEasy
0136Single NumberEasy
0137Single Number IIMedium
0190Reverse BitsEasy
0191Number of 1 BitsEasy

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.

Free to download. Check it runs on your machine, then pick a plan.