Apply Bitwise Operations to Make Strings Equal Problem
Description
LeetCode Problem 2546.
You are given two 0-indexed binary strings s and target of the same length n. You can do the following operation on s any number of times:
- Choose two different indices
iandjwhere0 <= i, j < n. - Simultaneously, replace
s[i]with (s[i]ORs[j]) ands[j]with (s[i]XORs[j]).
For example, if s = "0110", you can choose i = 0 and j = 2, then simultaneously replace s[0] with (s[0] OR s[2] = 0 OR 1 = 1), and s[2] with (s[0] XOR s[2] = 0 XOR 1 = 1), so we will have s = "1110".
Return true if you can make the string s equal to target, or false otherwise.
Example 1:
Input: s = "1010", target = "0110"
Output: true
Explanation: We can do the following operations:
- Choose i = 2 and j = 0. We have now s = "0010".
- Choose i = 2 and j = 1. We have now s = "0110".
Since we can make s equal to target, we return true.
Example 2:
Input: s = "11", target = "00"
Output: false
Explanation: It is not possible to make s equal to target with any number of operations.
Constraints:
n == s.length == target.length2 <= n <= 10^5sandtargetconsist of only the digits0and1.
Solution
Approach: Observation
An operation picks two positions and replaces them with their OR and XOR. If both are 0 the pair stays 00. If at least one is 1, the pair becomes one 1 and one 0 in some order or two 1s, so a 1 is never completely lost and one 1 can be moved around and copied.
A string with no 1 can never get one, and a string with at least one 1 can never lose all of them. With at least one 1 available we can reach any arrangement, so the strings can be made equal exactly when both contain a 1 or neither does.
Complexity: O(n) time and O(1) extra space.
class Solution:
def makeStringsEqual(self, s: str, target: str) -> bool:
return ("1" in s) == ("1" in target)