#3849

Maximum Bitwise XOR After Rearrangement

Medium
StringGreedyBit ManipulationBit ManipulationGreedy
LeetCode ↗

Approaches

Brute ForceOptimal
Complexity Comparison
Brute ForceOptimal Solution
Time
O(n²)
O(n)
Space
O(1)
O(n)
💡

Intuition

Time O(n)Space O(n)

To maximize the XOR, pair '1's in s with '0's in t and vice versa. Count the bits in t and construct the best arrangement.

⚙️

Algorithm

3 steps
  1. 1Step 1: Count the number of '0's and '1's in t.
  2. 2Step 2: For each bit in s, match '1' with '0' from t if available, otherwise use '1' from t.
  3. 3Step 3: Construct the result based on the matches.
solution.py12 lines
1def maxXOR(s, t):
2    count0 = t.count('0')
3    count1 = t.count('1')
4    result = []
5    for char in s:
6        if char == '1' and count0 > 0:
7            result.append('0')
8            count0 -= 1
9        else:
10            result.append('1')
11            count1 -= 1
12    return ''.join(result)

Complexity note: Counting bits is O(n) and constructing the result is also O(n), making it efficient.

  • 1Maximize XOR by pairing opposite bits.
  • 2Count bits to determine optimal arrangement.

Solutions and explanations are original Tejav content. Problem titles © LeetCode — use the LeetCode button above for the full problem statement.