Off-by-one on range boundaries
Wrong move: Loop endpoints miss first/last candidate.
Usually fails on: Fails on minimal arrays and exact-boundary answers.
Fix: Re-derive loops from inclusive/exclusive ranges before coding.
Break down a hard problem into reliable checkpoints, edge-case handling, and complexity trade-offs.
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] < 210Problem summary: 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.
Start with the most direct exhaustive search. That gives a correctness anchor before optimizing.
Pattern signal: Array · Hash Map · Dynamic Programming · Bit Manipulation
[1,2,0,3,0] 1
[3,4,5,2,1,7,3,4,7] 3
[1,2,4,1,2,5,1,2,6] 3
maximum-xor-score-subarray-queries)Source-backed implementations are provided below for direct study and interview prep.
// Accepted solution for LeetCode #1787: Make the XOR of All Segments Equal to Zero
class Solution {
public int minChanges(int[] nums, int k) {
int n = 1 << 10;
Map<Integer, Integer>[] cnt = new Map[k];
Arrays.setAll(cnt, i -> new HashMap<>());
int[] size = new int[k];
for (int i = 0; i < nums.length; ++i) {
int j = i % k;
cnt[j].merge(nums[i], 1, Integer::sum);
size[j]++;
}
int[] f = new int[n];
final int inf = 1 << 30;
Arrays.fill(f, inf);
f[0] = 0;
for (int i = 0; i < k; ++i) {
int[] g = new int[n];
Arrays.fill(g, min(f) + size[i]);
for (int j = 0; j < n; ++j) {
for (var e : cnt[i].entrySet()) {
int v = e.getKey(), c = e.getValue();
g[j] = Math.min(g[j], f[j ^ v] + size[i] - c);
}
}
f = g;
}
return f[0];
}
private int min(int[] arr) {
int mi = arr[0];
for (int v : arr) {
mi = Math.min(mi, v);
}
return mi;
}
}
// Accepted solution for LeetCode #1787: Make the XOR of All Segments Equal to Zero
func minChanges(nums []int, k int) int {
n := 1 << 10
cnt := make([]map[int]int, k)
for i := range cnt {
cnt[i] = map[int]int{}
}
size := make([]int, k)
for i, v := range nums {
cnt[i%k][v]++
size[i%k]++
}
f := make([]int, n)
for i := 1; i < n; i++ {
f[i] = 0x3f3f3f3f
}
for i, sz := range size {
g := make([]int, n)
x := slices.Min(f) + sz
for i := range g {
g[i] = x
}
for j := 0; j < n; j++ {
for v, c := range cnt[i] {
g[j] = min(g[j], f[j^v]+sz-c)
}
}
f = g
}
return f[0]
}
# Accepted solution for LeetCode #1787: Make the XOR of All Segments Equal to Zero
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]
// Accepted solution for LeetCode #1787: Make the XOR of All Segments Equal to Zero
/**
* [1787] Make the XOR of All Segments Equal to Zero
*
* You are given an array nums and an integer k. The <font face="monospace">XOR</font> 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 [<u>1</u>,<u>2</u>,0,<u>3</u>,0] to from [<u>0</u>,<u>0</u>,0,<u>0</u>,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,<u>5</u>,<u>2</u>,<u>1</u>,7,3,4,7] to [3,4,<u>7</u>,<u>3</u>,<u>4</u>,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,<u>4,</u>1,2,<u>5</u>,1,2,<u>6</u>] to [1,2,<u>3</u>,1,2,<u>3</u>,1,2,<u>3</u>].
*
* Constraints:
*
* 1 <= k <= nums.length <= 2000
* 0 <= nums[i] < 2^10
*
*/
pub struct Solution {}
// problem: https://leetcode.com/problems/make-the-xor-of-all-segments-equal-to-zero/
// discuss: https://leetcode.com/problems/make-the-xor-of-all-segments-equal-to-zero/discuss/?currentPage=1&orderBy=most_votes&query=
// submission codes start here
impl Solution {
pub fn min_changes(nums: Vec<i32>, k: i32) -> i32 {
0
}
}
// submission codes end
#[cfg(test)]
mod tests {
use super::*;
#[test]
#[ignore]
fn test_1787_example_1() {
let nums = vec![1, 2, 0, 3, 0];
let k = 1;
let result = 3;
assert_eq!(Solution::min_changes(nums, k), result);
}
#[test]
#[ignore]
fn test_1787_example_2() {
let nums = vec![3, 4, 5, 2, 1, 7, 3, 4, 7];
let k = 3;
let result = 3;
assert_eq!(Solution::min_changes(nums, k), result);
}
#[test]
#[ignore]
fn test_1787_example_3() {
let nums = vec![1, 2, 4, 1, 2, 5, 1, 2, 6];
let k = 3;
let result = 3;
assert_eq!(Solution::min_changes(nums, k), result);
}
}
// Accepted solution for LeetCode #1787: Make the XOR of All Segments Equal to Zero
// Auto-generated TypeScript example from java.
function exampleSolution(): void {
}
// Reference (java):
// // Accepted solution for LeetCode #1787: Make the XOR of All Segments Equal to Zero
// class Solution {
// public int minChanges(int[] nums, int k) {
// int n = 1 << 10;
// Map<Integer, Integer>[] cnt = new Map[k];
// Arrays.setAll(cnt, i -> new HashMap<>());
// int[] size = new int[k];
// for (int i = 0; i < nums.length; ++i) {
// int j = i % k;
// cnt[j].merge(nums[i], 1, Integer::sum);
// size[j]++;
// }
// int[] f = new int[n];
// final int inf = 1 << 30;
// Arrays.fill(f, inf);
// f[0] = 0;
// for (int i = 0; i < k; ++i) {
// int[] g = new int[n];
// Arrays.fill(g, min(f) + size[i]);
// for (int j = 0; j < n; ++j) {
// for (var e : cnt[i].entrySet()) {
// int v = e.getKey(), c = e.getValue();
// g[j] = Math.min(g[j], f[j ^ v] + size[i] - c);
// }
// }
// f = g;
// }
// return f[0];
// }
//
// private int min(int[] arr) {
// int mi = arr[0];
// for (int v : arr) {
// mi = Math.min(mi, v);
// }
// return mi;
// }
// }
Use this to step through a reusable interview workflow for this problem.
Pure recursion explores every possible choice at each step. With two choices per state (take or skip), the decision tree has 2ⁿ leaves. The recursion stack uses O(n) space. Many subproblems are recomputed exponentially many times.
Each cell in the DP table is computed exactly once from previously solved subproblems. The table dimensions determine both time and space. Look for the state variables — each unique combination of state values is one cell. Often a rolling array can reduce space by one dimension.
Review these before coding to avoid predictable interview regressions.
Wrong move: Loop endpoints miss first/last candidate.
Usually fails on: Fails on minimal arrays and exact-boundary answers.
Fix: Re-derive loops from inclusive/exclusive ranges before coding.
Wrong move: Zero-count keys stay in map and break distinct/count constraints.
Usually fails on: Window/map size checks are consistently off by one.
Fix: Delete keys when count reaches zero.
Wrong move: An incomplete state merges distinct subproblems and caches incorrect answers.
Usually fails on: Correctness breaks on cases that differ only in hidden state.
Fix: Define state so each unique subproblem maps to one DP cell.