Problem solution · Java

Make the XOR of All Segments Equal to Zero

Make the XOR of All Segments Equal to Zero: a Java solution using dynamic programming. Learn the idea, check the complexity, and read the full code, with credit to walkccc LeetCode Solutions.

Technique
Dynamic programming
Source
walkccc LeetCode Solutions
Length
45 lines
Start with the idea.

Try the problem first. If you get stuck, read the approach below, then write your own solution. The full code is at the bottom.

Approach

Dynamic programming

For Make the XOR of All Segments Equal to Zero, the implementation records answers for smaller states and reuses them to build the requested result without repeating work.

  1. Define precisely what one DP state represents.
  2. Establish the base cases before transitions are evaluated.
  3. Process states in dependency order and combine only already-known values.

Code notes

  • 45 lines of Java from the credited upstream file 1787.java.
  • The implementation visibly relies on sequence storage, hash lookup, ordered lookup, cached states.
  • 6 loop blocks detected.

Complexity

Multiply the number of reachable states by the work performed for each transition, then include the stored state table in memory usage.

Check the problem constraints before deciding whether this complexity will pass.

Source

Code and credit

This code comes from walkccc LeetCode Solutions by P.-Y. Chen (walkccc) and is used under the MIT licence.

Full codeMake the XOR of All Segments Equal to Zero · JavaJava
Use this to learn the idea, then write your own version.
class Solution {  public int minChanges(int[] nums, int k) {    final int MAX = 1024;    final int n = nums.length;    // counts[i] := the counter that maps at the i-th position    Map<Integer, Integer>[] counts = new Map[k];    // dp[i][j] := the minimum number of elements to change s.t. XOR(nums[i..k - 1]) is j    int[][] dp = new int[k][MAX];     for (int i = 0; i < k; ++i)      counts[i] = new HashMap<>();     for (int i = 0; i < n; ++i)      counts[i % k].merge(nums[i], 1, Integer::sum);     Arrays.stream(dp).forEach(A -> Arrays.fill(A, n));     // Initialize the DP array.    for (int j = 0; j < MAX; ++j)      dp[k - 1][j] = countAt(n, k, k - 1) - counts[k - 1].getOrDefault(j, 0);     for (int i = k - 2; i >= 0; --i) {      // The worst-case scenario is changing all the i-th position numbers to a      // non-existent value in the current bucket.      final int changeAll = countAt(n, k, i) + Arrays.stream(dp[i + 1]).min().getAsInt();      for (int j = 0; j < MAX; ++j) {        dp[i][j] = changeAll;        for (Map.Entry<Integer, Integer> entry : counts[i].entrySet()) {          final int num = entry.getKey();          final int freq = entry.getValue();          // the cost to change every number in the i-th position to `num`          final int cost = countAt(n, k, i) - freq;          dp[i][j] = Math.min(dp[i][j], dp[i + 1][j ^ num] + cost);        }      }    }     return dp[0][0];  }   private int countAt(int n, int k, int i) {    return n / k + (n % k > i ? 1 : 0);  }} 

Did this explanation save you time? I'm a Grade 11 student building this free library to make difficult algorithms easier to understand.

Buy me a coffee ↗