Make the XOR of All Segments Equal to Zero - Problem
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.
A segment of size k starting at position i includes elements nums[i], nums[i+1], ..., nums[i+k-1].
Input & Output
Example 1 — Basic Case
$
Input:
nums = [1,2,0,3,1], k = 3
›
Output:
3
💡 Note:
We need segments [1,2,0], [2,0,3], [0,3,1] to all XOR to 0. One solution: change nums to [0,0,0,0,0], requiring 3 changes (positions 0,1,3).
Example 2 — Smaller Array
$
Input:
nums = [3,4,5,2], k = 2
›
Output:
2
💡 Note:
Segments are [3,4], [4,5], [5,2] with XORs 7, 1, 7. To make all XORs equal 0, we can change the array to [0,0,0,0], requiring 2 changes.
Example 3 — Minimum Size
$
Input:
nums = [1,2], k = 2
›
Output:
1
💡 Note:
Only one segment [1,2]. Need 1⊕2=3 to become 0. Change one element: [0,0] gives 0⊕0=0. Cost: 1 change.
Constraints
- 1 ≤ nums.length ≤ 2000
- 1 ≤ k ≤ nums.length
- 0 ≤ nums[i] < 210
Visualization
Tap to expand
💡
Explanation
AI Ready
💡 Suggestion
Tab
to accept
Esc
to dismiss
// Output will appear here after running code