Make the XOR of All Segments Equal to Zero Problem
Description
LeetCode Problem 1787.
You are given an array nums and an integer k. The XOR of a segment [left, right] where left <= right is the XOR of all the elements with indices between left and right, inclusive: nums[left] XOR nums[left+1] XOR ... XOR nums[right].
Return the minimum number of elements to change in the array such that the XOR of all segments of size k is equal to zero.
Example 1:
Input: nums = [1,2,0,3,0], k = 1
Output: 3
Explanation: Modify the array from [1,2,0,3,0] to from [0,0,0,0,0].
Example 2:
Input: nums = [3,4,5,2,1,7,3,4,7], k = 3
Output: 3
Explanation: Modify the array from [3,4,5,2,1,7,3,4,7] to [3,4,7,3,4,7,3,4,7].
Example 3:
Input: nums = [1,2,4,1,2,5,1,2,6], k = 3
Output: 3
Explanation: Modify the array from [1,2,4,1,2,5,1,2,6] to [1,2,3,1,2,3,1,2,3].
Constraints:
1 <= k <= nums.length <= 20000 <= nums[i] < 2^10
Solution
Approach: Dynamic Programming over XOR Values
If every window of length k has XOR 0, then two neighbouring windows give nums[i] == nums[i + k]. So the final array is periodic with period k: all positions with the same index modulo k hold the same value, and the XOR of the k group values must be 0.
Split the array into k groups by index modulo k; group i has size[i] elements, and cnt[i][v] counts how many of them equal v. Let f[j] be the minimum number of changes for the groups handled so far such that the XOR of their chosen values is j (values are below 210, so j < 1024).
For the next group i and a target XOR j:
- Choose a value
vthat already appears in the group: it costssize[i] - cnt[i][v]changes on top off[j ^ v]. - Or choose a value that does not appear, changing the whole group:
size[i]plus the smallestfoverall. Anyjcan be reached this way by picking a suitable fresh value.
The answer is f[0] after the last group.
Complexity: O(210 · n) time, since each group tries each of its distinct values for each j, and O(210 + n) space.
from collections import Counter
from math import inf
class Solution:
def minChanges(self, nums: List[int], k: int) -> int:
n = 1 << 10
cnt = [Counter() for _ in range(k)]
size = [0] * k
for i, v in enumerate(nums):
cnt[i % k][v] += 1
size[i % k] += 1
f = [inf] * n
f[0] = 0
for i in range(k):
g = [min(f) + size[i]] * n
for j in range(n):
for v, c in cnt[i].items():
g[j] = min(g[j], f[j ^ v] + size[i] - c)
f = g
return f[0]