LeetCode 1879. Minimum XOR Sum of Two Arrays Solution in Java, C++, Python & More | Explanation + Code

CoderIndeed
0
1879. Minimum XOR Sum of Two Arrays

Description

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]) + ... + (nums1[n - 1] XOR nums2[n - 1]) (0-indexed).

  • For example, the XOR sum of [1,2,3] and [3,2,1] is equal to (1 XOR 3) + (2 XOR 2) + (3 XOR 1) = 2 + 0 + 2 = 4.

Rearrange the elements of nums2 such that the resulting XOR sum is minimized.

Return the XOR sum after the rearrangement.

 

Example 1:

Input: nums1 = [1,2], nums2 = [2,3]
Output: 2
Explanation: Rearrange nums2 so that it becomes [3,2].
The XOR sum is (1 XOR 3) + (2 XOR 2) = 2 + 0 = 2.

Example 2:

Input: nums1 = [1,0,3], nums2 = [5,3,4]
Output: 8
Explanation: Rearrange nums2 so that it becomes [5,4,3]. 
The XOR sum is (1 XOR 5) + (0 XOR 4) + (3 XOR 3) = 4 + 4 + 0 = 8.

 

Constraints:

  • n == nums1.length
  • n == nums2.length
  • 1 <= n <= 14
  • 0 <= nums1[i], nums2[i] <= 107

Solutions

Solution 1

PythonJavaC++GoTypeScript
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](code-box)

Solution 2

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

Solution 3

PythonJavaC++GoTypeScript
class Solution: def minimumXORSum(self, nums1: List[int], nums2: List[int]) -> int: n = len(nums2) f = [inf] * (1 << n) f[0] = 0 for i in range(1, 1 << n): k = i.bit_count() - 1 for j in range(n): if i >> j & 1: f[i] = min(f[i], f[i ^ (1 << j)] + (nums1[k] ^ nums2[j])) return f[-1](code-box)

Post a Comment

0Comments

Post a Comment (0)

#buttons=(Accept !) #days=(20)

Our website uses cookies to enhance your experience. Check Now
Accept !