#3599
Partition Array to Minimize XOR
MediumArrayDynamic ProgrammingBit ManipulationPrefix SumDynamic ProgrammingPrefix Sum
Approaches
Brute ForceOptimal
Complexity Comparison
| Brute Force | Optimal Solution★ | |
|---|---|---|
| Time | O(n²) | O(n² * k) |
| Space | O(1) | O(n * k) |
💡
Intuition
Time O(n² * k)Space O(n * k)
We can use dynamic programming to efficiently compute the minimum possible value of the maximum XOR among k subarrays. By precomputing the XOR values, we can reduce redundant calculations.
⚙️
Algorithm
3 steps- 1Step 1: Precompute the prefix XOR array where pre[i] = nums[0] ^ ... ^ nums[i].
- 2Step 2: Use dynamic programming to find the minimum maximum XOR for k partitions by iterating through possible partition points.
- 3Step 3: Update the DP table based on previously computed values and the current subarray XOR.
solution.py11 lines
1def minXor(nums, k):
2 n = len(nums)
3 pre = [0] * (n + 1)
4 for i in range(n): pre[i + 1] = pre[i] ^ nums[i]
5 dp = [[float('inf')] * (k + 1) for _ in range(n + 1)]
6 dp[0][0] = 0
7 for i in range(1, n + 1):
8 for j in range(1, k + 1):
9 for p in range(i):
10 dp[i][j] = min(dp[i][j], max(dp[p][j - 1], pre[i] ^ pre[p]))
11 return dp[n][k]ℹ
Complexity note: The complexity arises from filling the DP table, iterating through n and k, leading to a quadratic relation.
- 1Understanding XOR properties can simplify calculations.
- 2Dynamic programming can optimize partitioning problems.
Solutions and explanations are original Tejav content. Problem titles © LeetCode — use the LeetCode button above for the full problem statement.