#1879
Minimum XOR Sum of Two Arrays
HardArrayDynamic ProgrammingBit ManipulationBitmaskDynamic ProgrammingBitmaskingSubset Problems
Approaches
Brute ForceOptimal
Complexity Comparison
| Brute Force | Optimal Solution★ | |
|---|---|---|
| Time | O(n!) | O(n * 2^n) |
| Space | O(n) | O(2^n) |
💡
Intuition
Time O(n * 2^n)Space O(2^n)
The optimal solution uses dynamic programming with bitmasking to efficiently explore all possible selections of nums2 without generating all permutations explicitly. This reduces the time complexity significantly.
⚙️
Algorithm
3 steps- 1Step 1: Use a bitmask to represent the selection of elements from nums2.
- 2Step 2: For each bitmask, calculate the XOR sum by selecting corresponding elements from nums2.
- 3Step 3: Track the minimum XOR sum across all bitmask selections.
solution.py13 lines
1def minXORSum(nums1, nums2):
2 n = len(nums1)
3 dp = [float('inf')] * (1 << n)
4 dp[0] = 0
5 for mask in range(1 << n):
6 count = bin(mask).count('1')
7 if count > n:
8 continue
9 for j in range(n):
10 if mask & (1 << j) == 0:
11 new_mask = mask | (1 << j)
12 dp[new_mask] = min(dp[new_mask], dp[mask] + (nums1[count] ^ nums2[j]))
13 return dp[(1 << n) - 1]ℹ
Complexity note: The time complexity is O(n * 2^n) because we iterate through all subsets of nums2 (2^n) and for each subset, we perform O(n) operations. The space complexity is O(2^n) for the dp array storing results for each subset.
- 1Using bitmasking allows us to efficiently explore combinations without generating all permutations.
- 2Dynamic programming can significantly reduce the time complexity for problems involving subsets.
Solutions and explanations are original Tejav content. Problem titles © LeetCode — use the LeetCode button above for the full problem statement.