Data Structures19 sections · 729 units
Open in Course

Range XOR Solution

Prefix XOR approach

function solve(arr, queries):
    n = arr.length
    // Build prefix XOR
    prefix = array of size (n + 1), filled with 0
    for i = 0 to n - 1:
        prefix[i + 1] = prefix[i] ^ arr[i]

    results = empty list
    for each (l, r) in queries:
        // XOR of [l, r] = prefix[r+1] ^ prefix[l]
        results.append(prefix[r + 1] ^ prefix[l])

    return results

Time: O(n+q)O(n + q). This is faster than any sparse table approach.

Lesson: sparse tables are powerful for idempotent operations, but simpler techniques might be better for specific operations like XOR.