Problem
You are given an integer array nums
of length n
and a 2D integer array queries
of length q
, where each query is one of the following three types:
-
Update:
queries[i] = [1, index, value]
Setnums[index] = value
. -
Range XOR Query:
queries[i] = [2, left, right]
Compute the bitwise XOR of all elements in the subarraynums[left...right]
, and record this result. -
Reverse Subarray:
queries[i] = [3, left, right]
Reverse the subarraynums[left...right]
in place.
Return an array of the results of all range XOR queries in the order they were encountered.
Examples
Example 1
|
|
Example 2
|
|
Constraints
1 <= nums.length <= 105
0 <= nums[i] <= 109
1 <= queries.length <= 105
queries[i].length == 3
queries[i][0] ∈ {1, 2, 3}
- If
queries[i][0] == 1
:
0 <= index < nums.length
0 <= value <= 109
- If
queries[i][0] == 2
orqueries[i][0] == 3
:
0 <= left <= right < nums.length
Solution
Method 1 – Segment Tree with Lazy Propagation
Intuition
The problem requires efficiently handling range XOR queries and subarray reversals. A segment tree with lazy propagation can efficiently support both range XOR and range reverse operations by maintaining additional information for each segment.
Approach
- Build a segment tree where each node stores the XOR of its segment and a flag for pending reversals.
- For a range reversal, propagate the reversal flag down the tree and swap children as needed.
- For a range XOR query, use the segment tree to get the XOR in O(log n) time, considering any pending reversals.
- Use lazy propagation to ensure all operations are efficient.
Code
|
|
|
|
|
|
|
|
|
|
|
|
|
|
Complexity
- ⏰ Time complexity:
O(log n)
per query or update, since each operation traverses the height of the segment tree. - 🧺 Space complexity:
O(n)
, for the segment tree nodes.