Similar Problems
Similar Problems not available
Minimum Flips To Make A Or B Equal To C - Leetcode Solution
Companies:
LeetCode: Minimum Flips To Make A Or B Equal To C Leetcode Solution
Difficulty: Medium
Topics: bit-manipulation
Problem:
Given three binary strings a, b and c, return the minimum number of flips to make a or b equal to c. If it is impossible, return -1.
The flip operation consists of changing any 0 to 1 or vice versa.
Constraints:
- 1 <= a.length, b.length, c.length <= 100
- a, b, and c consist of only 0's and 1's.
Solution:
To solve this problem, we need to follow the below approach:
Step 1:
Traverse through the given strings a, b, and c simultaneously and perform the following actions:
- If c[i] is 0, check if either a[i] or b[i] is also 0. If neither a[i] nor b[i] is 0, then it is impossible to make c equal to either a or b, so return -1.
- If c[i] is 1, check if either a[i] or b[i] is also 1. If neither a[i] nor b[i] is 1, then it is impossible to make c equal to either a or b, so return -1.
Step 2:
If it is possible to make c equal to either a or b, then traverse through the given strings a, b, and c simultaneously again and perform the following actions:
- If c[i] == 0 and both a[i] and b[i] are 1, then we need to flip one of these bits to 0 to make a or b equal to c. The minimum number of flips required is 1.
- If c[i] == 1 and both a[i] and b[i] are 0, then we need to flip one of these bits to 1 to make a or b equal to c. The minimum number of flips required is 1.
- If c[i] == 0 and either a[i] or b[i] is 1, then no flip is required to make a or b equal to c at this position.
- If c[i] == 1 and either a[i] or b[i] is 0, then no flip is required to make a or b equal to c at this position.
Step 3:
Return the total number of flips required to make a or b equal to c.
Code:
Here is the Python code for the above approach:
def minFlips(self, a: str, b: str, c: str) -> int: n = len(a) flips = 0 for i in range(n): if c[i] == '0': if a[i] == '1' or b[i] == '1': if a[i] == '1' and b[i] == '1': flips += 2 else: flips += 1 else: continue else: if a[i] == '0' and b[i] == '0': flips += 1 else: continue return flips if flips != 0 else -1
Explanation:
- We start by traversing through the given strings a, b, and c simultaneously (line 3).
- We check if it is possible to make c equal to either a or b and return -1 if it is not possible (lines 5-12).
- We then traverse through the given strings a, b, and c simultaneously again and calculate the total number of flips required to make a or b equal to c (lines 14-22).
- Finally, we return the total number of flips required or -1 if no flips are required (lines 24-26).
Complexity Analysis:
- Time Complexity: O(n), where n is the length of a, b, and c.
- Space Complexity: O(1), as we only use constant extra space.
Minimum Flips To Make A Or B Equal To C Solution Code
1