Similar Problems
Similar Problems not available
Minimum Xor Sum Of Two Arrays - Leetcode Solution
Companies:
LeetCode: Minimum Xor Sum Of Two Arrays Leetcode Solution
Difficulty: Hard
Topics: dynamic-programming bit-manipulation array
Problem Statement:
Given two integer arrays nums1 and nums2, return the minimum bitwise XOR sum of any two elements each taken from nums1 and nums2.
Example 1:
Input: nums1 = [1,2], nums2 = [2,3] Output: 2 Explanation: The optimal choice of elements is:
- nums1[0] = 1 and nums2[1] = 3, which gives bitwise XOR sum = 1 XOR 3 = 2. Therefore, the minimum bitwise XOR sum is 2.
Example 2:
Input: nums1 = [1,0,3], nums2 = [5,3,4] Output: 8 Explanation: The optimal choice of elements is:
- nums1[0] = 1 and nums2[1] = 3, which gives bitwise XOR sum = 1 XOR 3 = 2.
- nums1[2] = 3 and nums2[2] = 4, which gives bitwise XOR sum = 3 XOR 4 = 7. Therefore, the minimum bitwise XOR sum is 2 + 7 = 8.
Approach:
We can solve this problem by using dynamic programming. Let's define dp[i][j] as the minimum XOR sum of any two elements each taken from the first i elements of nums1 and the first j elements of nums2.
To calculate dp[i][j], we can choose two elements from nums1 and nums2 as nums1[k] and nums2[l], where 0 <= k <= i-1 and 0 <= l <= j-1. Then the minimum XOR sum of these two elements is nums1[k] XOR nums2[l], and the remaining elements can be chosen from dp[k][l+1], dp[k+1][l] and dp[k+1][l+1].
Therefore, the recursive formula is:
dp[i][j] = min(nums1[k] XOR nums2[l] + dp[k][l+1], nums1[k] XOR nums2[l] + dp[k+1][l], dp[k+1][l+1])
where 0 <= k <= i-1 and 0 <= l <= j-1.
The base case is dp[0][0] = 0, i.e. the minimum XOR sum when both arrays are empty is 0.
Finally, the answer is dp[n1][n2], where n1 and n2 are the lengths of nums1 and nums2, respectively.
Code:
Here is the Python code for the above approach:
def minimumXORSum(nums1, nums2): n1, n2 = len(nums1), len(nums2) dp = [[0] * (n2+1) for _ in range(n1+1)] for i in range(n1-1, -1, -1): dp[i][n2] = dp[i+1][n2] + nums1[i] for j in range(n2-1, -1, -1): dp[n1][j] = dp[n1][j+1] + nums2[j] for i in range(n1-1, -1, -1): for j in range(n2-1, -1, -1): dp[i][j] = min(nums1[i] ^ nums2[j] + dp[i+1][j+1], nums1[i] + dp[i+1][j], nums2[j] + dp[i][j+1]) return dp[0][0]
The time complexity of the above implementation is O(n1*n2), where n1 and n2 are the lengths of nums1 and nums2, respectively.
Minimum Xor Sum Of Two Arrays Solution Code
1