Maximum Bitwise XOR After Rearrangement Problem
#3849
Try it yourself first
Five languages, sample and hidden tests, right in the browser.
Practice it as an interview
Talk through your solution with an AI interviewer while you code.
Description
LeetCode Problem 3849.
You are given two binary strings s and t, each of length n.
You may rearrange the characters of t in any order, but s must remain unchanged.
Return a binary string of length n representing the maximum integer value obtainable by taking the bitwise XOR of s and rearranged t.
Example 1:
Input: s = "101", t = "011"
Output: "110"
Explanation:
- One optimal rearrangement of t is "011".
- The bitwise XOR of s and rearranged t is "101" XOR "011" = "110", which is the maximum possible.
Example 2:
Input: s = "0110", t = "1110"
Output: "1101"
Explanation:
- One optimal rearrangement of t is "1011".
- The bitwise XOR of s and rearranged t is "0110" XOR "1011" = "1101", which is the maximum possible.
Example 3:
Input: s = "0101", t = "1001"
Output: "1111"
Explanation:
- One optimal rearrangement of t is "1010".
- The bitwise XOR of s and rearranged t is "0101" XOR "1010" = "1111", which is the maximum possible.
Constraints:
1 <= n == s.length == t.length <= 2 * 10^5s[i]andt[i]are either'0'or'1'.
Solution
Approach: Greedy
Count the zeros and ones in t. Go through s from the most significant bit. To get a 1 in the result we need a bit in t that differs from s[i]: if one is left, use it and write 1. Otherwise we must use a bit equal to s[i] and the result bit is 0. Taking a 1 as early as possible is always best, because a higher bit outweighs all lower bits together.
Complexity: O(n) time and O(n) space for the answer.
class Solution:
def maximumXor(self, s: str, t: str) -> str:
cnt = [0, 0]
for c in t:
cnt[int(c)] += 1
ans = ['0'] * len(s)
for i, c in enumerate(s):
x = int(c)
if cnt[x ^ 1]:
cnt[x ^ 1] -= 1
ans[i] = '1'
else:
cnt[x] -= 1
return ''.join(ans)