XOR After Range Multiplication Queries I Problem
#3653
Try it yourself first
Five languages, sample and hidden tests, right in the browser.
Practice it as an interview
Talk through your solution with an AI interviewer while you code.
Description
LeetCode Problem 3653.
You are given an integer array nums of length n and a 2D integer array queries of size q, where queries[i] = [l_i, r_i, k_i, v_i].
For each query, you must apply the following operations in order:
- Set
idx = l_i. - While
idx <= r_i:- Update:
nums[idx] = (nums[idx] * v_i) % (10^9 + 7) - Set
idx += k_i.
- Update:
Return the bitwise XOR of all elements in nums after processing all queries.
Example 1:
Input: nums = [1,1,1], queries = [[0,2,1,4]]
Output: 4
Explanation:
- A single query [0, 2, 1, 4] multiplies every element from index 0 through index 2 by 4.
- The array changes from [1, 1, 1] to [4, 4, 4].
- The XOR of all elements is 4 ^ 4 ^ 4 = 4.
Example 2:
Input: nums = [2,3,1,5,4], queries = [[1,4,2,3],[0,2,1,2]]
Output: 31
Explanation:
- The first query [1, 4, 2, 3] multiplies the elements at indices 1 and 3 by 3, transforming the array to [2, 9, 1, 15, 4].
- The second query [0, 2, 1, 2] multiplies the elements at indices 0, 1, and 2 by 2, resulting in [4, 18, 2, 15, 4].
- Finally, the XOR of all elements is 4 ^ 18 ^ 2 ^ 15 ^ 4 = 31.
Constraints:
1 <= n == nums.length <= 10^31 <= nums[i] <= 10^91 <= q == queries.length <= 10^3queries[i] = [l_i, r_i, k_i, v_i]0 <= l_i <= r_i < n1 <= k_i <= n1 <= v_i <= 10^5
Solution
Approach: Simulation
The limits are small, so just do what the statement says. For each query [l, r, k, v], walk idx = l, l + k, l + 2k, ... up to r and set nums[idx] = nums[idx] * v % (10^9 + 7). Then XOR all elements together.
Complexity: O(q * n / k) time per query in the worst case (at most O(q * n)) and O(1) extra space.
from functools import reduce
from operator import xor
class Solution:
def xorAfterQueries(self, nums: List[int], queries: List[List[int]]) -> int:
mod = 10**9 + 7
for l, r, k, v in queries:
for idx in range(l, r + 1, k):
nums[idx] = nums[idx] * v % mod
return reduce(xor, nums)