Program to make the XOR of all segments equal to zero in Python

Suppose we have an array called nums and another value k. The XOR of a segment [left, right] (left <= right) is the XOR of all elements whose indices are in between left and right (inclusive).

We have to find the minimum number of elements to change in the array such that the XOR of all segments of size k is same as zero.

So, if the input is like nums = [3,4,5,2,1,7,3,4,7], k = 3, then the output will be 3 because we can modify elements at indices 2, 3, 4 to make the array [3,4,7,3,4,7,3,4,7].

Approach

To solve this, we will follow these steps −

  • LIMIT := 1024 (maximum possible value)

  • temp := make a 2D array of size LIMIT x k to count frequency of each value at each position

  • For each index i and value x in nums, increment temp[i mod k][x]

  • dp := dynamic programming array to track maximum elements we can keep

  • For each position, try all possible XOR combinations

  • Return total elements minus maximum elements we can keep

Example

Let us see the following implementation to get better understanding −

def solve(nums, k):
    LIMIT = 2**10
    # Count frequency of each value at each position modulo k
    temp = [[0 for _ in range(LIMIT)] for _ in range(k)]
    for i, x in enumerate(nums):
        temp[i % k][x] += 1
    
    # dp[xor] = maximum number of elements we can keep with XOR = xor
    dp = [-2000 for _ in range(LIMIT)]
    dp[0] = 0
    
    for row in temp:
        maxprev = max(dp)
        new_dp = [maxprev for _ in range(LIMIT)]
        
        for i, cnt in enumerate(row):
            if cnt > 0:
                for j, prev in enumerate(dp):
                    new_dp[i ^ j] = max(new_dp[i ^ j], prev + cnt)
        
        dp = new_dp
    
    # Return minimum changes needed
    return len(nums) - dp[0]

# Test the function
nums = [3, 4, 5, 2, 1, 7, 3, 4, 7]
k = 3
result = solve(nums, k)
print(f"Minimum changes needed: {result}")
Minimum changes needed: 3

How It Works

The algorithm works by using dynamic programming where:

  • We group elements by their position modulo k

  • For each position group, we count frequency of each value

  • dp[xor] represents the maximum number of elements we can keep to achieve XOR value xor

  • We iterate through each position and update possible XOR values

  • Finally, we return total elements minus maximum elements we can keep with XOR = 0

Step-by-Step Execution

def solve_with_debug(nums, k):
    LIMIT = 2**10
    temp = [[0 for _ in range(LIMIT)] for _ in range(k)]
    
    print("Input array:", nums)
    print("k =", k)
    
    # Count frequencies
    for i, x in enumerate(nums):
        temp[i % k][x] += 1
        print(f"Element {x} at position {i} goes to group {i % k}")
    
    # Show frequency distribution
    for pos in range(k):
        non_zero = [(val, count) for val, count in enumerate(temp[pos]) if count > 0]
        if non_zero:
            print(f"Position group {pos}: {non_zero}")
    
    dp = [-2000 for _ in range(LIMIT)]
    dp[0] = 0
    
    for row in temp:
        maxprev = max(dp)
        new_dp = [maxprev for _ in range(LIMIT)]
        
        for i, cnt in enumerate(row):
            if cnt > 0:
                for j, prev in enumerate(dp):
                    new_dp[i ^ j] = max(new_dp[i ^ j], prev + cnt)
        
        dp = new_dp
    
    return len(nums) - dp[0]

nums = [3, 4, 5, 2, 1, 7, 3, 4, 7]
k = 3
result = solve_with_debug(nums, k)
print(f"\nMinimum changes needed: {result}")
Input array: [3, 4, 5, 2, 1, 7, 3, 4, 7]
k = 3
Element 3 at position 0 goes to group 0
Element 4 at position 1 goes to group 1
Element 5 at position 2 goes to group 2
Element 2 at position 3 goes to group 0
Element 1 at position 4 goes to group 1
Element 7 at position 5 goes to group 2
Element 3 at position 6 goes to group 0
Element 4 at position 7 goes to group 1
Element 7 at position 8 goes to group 2
Position group 0: [(2, 1), (3, 2)]
Position group 1: [(1, 1), (4, 2)]
Position group 2: [(5, 1), (7, 2)]

Minimum changes needed: 3

Conclusion

This dynamic programming solution efficiently finds the minimum changes needed by grouping elements by position and maximizing the number of elements we can keep to achieve XOR = 0. The time complexity is O(n + k * LIMIT²) where LIMIT is the maximum possible value.

Updated on: 2026-03-26T14:46:49+05:30

404 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements