Partition Array to Minimize XOR Problem
#3599
Try it yourself first
Five languages, sample and hidden tests, right in the browser.
Practice it as an interview
Talk through your solution with an AI interviewer while you code.
Description
LeetCode Problem 3599.
You are given an integer array nums and an integer k.
Your task is to partition nums into k non-empty subarrays. For each subarray, compute the bitwise XOR of all its elements.
Return the minimum possible value of the maximum XOR among these k subarrays.
Example 1:
Input: nums = [1,2,3], k = 2
Output: 1
Explanation:
The optimal partition is [1] and [2, 3].
- XOR of the first subarray is 1.
- XOR of the second subarray is 2 XOR 3 = 1.
The maximum XOR among the subarrays is 1, which is the minimum possible.
Example 2:
Input: nums = [2,3,3,2], k = 3
Output: 2
Explanation:
The optimal partition is [2], [3, 3], and [2].
- XOR of the first subarray is 2.
- XOR of the second subarray is 3 XOR 3 = 0.
- XOR of the third subarray is 2.
The maximum XOR among the subarrays is 2, which is the minimum possible.
Example 3:
Input: nums = [1,1,2,3,1], k = 2
Output: 0
Explanation:
The optimal partition is [1, 1] and [2, 3, 1].
- XOR of the first subarray is 1 XOR 1 = 0.
- XOR of the second subarray is 2 XOR 3 XOR 1 = 0.
The maximum XOR among the subarrays is 0, which is the minimum possible.
Constraints:
1 <= nums.length <= 2501 <= nums[i] <= 10^91 <= k <= n
Solution
Approach: Dynamic Programming
Let f[i][j] be the smallest possible largest XOR when the first i elements are split into j subarrays. Start with f[0][0] = 0 and everything else infinite.
With a prefix XOR array g, the XOR of the subarray after position h up to i is g[i] ^ g[h]. Choose where the last subarray starts:
f[i][j] = min over h from j-1 to i-1 of max(f[h][j-1], g[i] ^ g[h])
The answer is f[n][k].
Complexity: O(n2 * k) time and O(n * k) extra space.
from math import inf
min = lambda a, b: a if a < b else b
max = lambda a, b: a if a > b else b
class Solution:
def minXor(self, nums: List[int], k: int) -> int:
n = len(nums)
g = [0] * (n + 1)
for i, x in enumerate(nums, 1):
g[i] = g[i - 1] ^ x
f = [[inf] * (k + 1) for _ in range(n + 1)]
f[0][0] = 0
for i in range(1, n + 1):
for j in range(1, min(i, k) + 1):
for h in range(j - 1, i):
f[i][j] = min(f[i][j], max(f[h][j - 1], g[i] ^ g[h]))
return f[n][k]