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
XOR of All Segments Equal to Zero INPUT Array nums: 1 i=0 2 i=1 0 i=2 3 i=3 1 i=4 k = 3 Size-3 Segments: [1,2,0] XOR = 3 [2,0,3] XOR = 1 [0,3,1] XOR = 2 Goal: All XOR = 0 ALGORITHM STEPS 1 Pattern Recognition nums[i] XOR nums[i+k] = 0 --> nums[i] = nums[i+k] 2 Group by Position Group elements by i mod k Group 0 [1, 3] i%3=0 Group 1 [2, 1] i%3=1 Group 2 [0] i%3=2 3 Frequency Count Count freq in each group 4 Greedy Selection Pick values so XOR = 0 Minimize changes needed min_changes = n - max_kept with g0 XOR g1 XOR g2 = 0 FINAL RESULT Optimal Selection: For all XOR = 0: g0=0, g1=0, g2=0 0 XOR 0 XOR 0 = 0 Changes Required: Position 0: 1 --> 0 (change) Position 1: 2 --> 0 (change) Position 2: 0 --> 0 (keep) Position 3: 3 --> 0 (change) Result Array: 0 0 0 0 1 OUTPUT 3 Key Insight: For all size-k segments to have XOR=0, we need nums[i] = nums[i+k] for all valid i. This means elements at positions i mod k must be identical. Group elements by (index mod k), then use greedy/DP to pick values for each group such that their XOR equals 0 with minimum changes. TutorialsPoint - Make the XOR of All Segments Equal to Zero | Optimized Greedy with Pattern Recognition
Asked in
Google 15 Microsoft 12 Amazon 8
18.5K Views
Medium Frequency
~35 min Avg. Time
427 Likes
Ln 1, Col 1
Smart Actions
💡 Explanation
AI Ready
💡 Suggestion Tab to accept Esc to dismiss
// Output will appear here after running code
Code Editor Closed
Click the red button to reopen