Skip to main content

Command Palette

Search for a command to run...

Solving Leetcode Interviews in Seconds with AI: Minimum Flips to Make a OR b Equal to c

Updated
3 min read

Introduction

In this blog post, we will explore how to solve the LeetCode problem "1318" using AI. LeetCode is a popular platform for preparing for coding interviews, and with the help of AI tools like Chatmagic, we can generate solutions quickly and efficiently - helping you pass the interviews and get the job offer without having to study for months.

Problem Statement

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 ). (bitwise OR operation). Flip operation consists of change any single bit 1 to 0 or change the bit 0 to 1 in their binary representation. Example 1:
Input: a = 2, b = 6, c = 5 Output: 3 Explanation: After flips a = 1 , b = 4 , c = 5 such that (a OR b == c) Example 2: Input: a = 4, b = 2, c = 7 Output: 1 Example 3: Input: a = 1, b = 2, c = 3 Output: 0 Constraints: 1 <= a <= 10^9 1 <= b <= 10^9 1 <= c <= 10^9

Explanation

Here's the solution:

  • High-level approach: Iterate through the bits of a, b, and c from right to left. For each bit position, determine the number of flips required to make (a OR b) == c. Specifically, if the bit in c is 0, and the corresponding bits in a and b are both 1, then two flips are needed. If the bit in c is 1, and both a and b bits are 0, one flip is required.

  • Complexity: O(log(N)) runtime, O(1) storage where N is the maximum of a,b, and c.

Code

    def minFlips(a: int, b: int, c: int) -> int:
    """
    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 ).
    Flip operation consists of change any single bit 1 to 0 or change the bit 0 to 1 in their binary representation.

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

    Example 2:
    Input: a = 4, b = 2, c = 7
    Output: 1

    Example 3:
    Input: a = 1, b = 2, c = 3
    Output: 0

    Constraints:
    1 <= a <= 10^9
    1 <= b <= 10^9
    1 <= c <= 10^9
    """
    flips = 0
    while a > 0 or b > 0 or c > 0:
        bit_a = a & 1
        bit_b = b & 1
        bit_c = c & 1

        if (bit_a | bit_b) != bit_c:
            if bit_c == 0:
                if bit_a == 1 and bit_b == 1:
                    flips += 2
                else:
                    flips += 1
            else:
                flips += 1

        a >>= 1
        b >>= 1
        c >>= 1

    return flips

More from this blog

C

Chatmagic blog

2894 posts