Minimum XOR Sum of Two Arrays — LeetCode 1879 Python Solution

HardBit ManipulationArrayDynamic ProgrammingBitmask
Problem
#1879
Reading time
2 min

The problem

You are given two integer arrays nums1 and nums2 of length n. The XOR sum of the two integer arrays is (nums1[0] XOR nums2[0]) + (nums1[1] XOR nums2[1]) + ...

Example

Input
nums1 = [1,2], nums2 = [2,3]
Output
2
Explanation
Rearrange nums2 so that it becomes [3,2].

Python solution

Python
class Solution:
    def minimumXORSum(self, nums1: List[int], nums2: List[int]) -> int:
        n = len(nums2)
        f = [[inf] * (1 << n) for _ in range(n + 1)]
        f[0][0] = 0
        for i, x in enumerate(nums1, 1):
            for j in range(1 << n):
                for k in range(n):
                    if j >> k & 1:
                        f[i][j] = min(f[i][j], f[i - 1][j ^ (1 << k)] + (x ^ nums2[k]))
        return f[-1][-1]

Complexity

MeasureComplexity
TimeO(n·m) (typical)
SpaceO(n·m) or optimized auxiliary

Pattern: Bit Manipulation

Use XOR, masks and the low-bit trick to replace whole data structures with an integer. LeetCode 1879. Minimum XOR Sum of Two Arrays is filed here because LeetCode tags it Bit Manipulation and Bitmask, which is the vocabulary this hub collects.

The bit manipulation guide has the Python template for the pattern and the 194 LeetCode problems that use it.

Related problems

Frequently asked questions

How hard is LeetCode 1879. Minimum XOR Sum of Two Arrays?
LeetCode 1879. Minimum XOR Sum of Two Arrays is rated Hard on LeetCode.
What topics does LeetCode 1879. Minimum XOR Sum of Two Arrays cover?
LeetCode 1879. Minimum XOR Sum of Two Arrays is tagged Bit Manipulation, Array, Dynamic Programming and Bitmask on LeetCode.

Stuck on problems like this in a live interview?

Stealth Interview is a desktop app for macOS and Windows. It reads the problem off your screen and returns a working solution with a step-by-step explanation and its time and space complexity — invisible to screen sharing.

Get Stealth Interview