Problem
You are given an array of positive integers nums
and a positive integer k
. You are also given a 2D array queries
, where queries[i] = [indexi, valuei, starti, xi]
.
You are allowed to perform an operation once on nums
, where you can remove any suffix from nums
such that nums
remains non-empty.
The x-value of nums
for a given x
is defined as the number of ways to perform this operation so that the product of the remaining elements leaves a remainder of x
modulo k
.
For each query in queries
you need to determine the x-value of nums
for xi
after performing the following actions:
- Update
nums[indexi]
tovaluei
. Only this step persists for the rest of the queries. - Remove the prefix
nums[0..(starti - 1)]
(wherenums[0..(-1)]
will be used to represent the empty prefix).
Return an array result
of size queries.length
where result[i]
is the answer for the ith
query.
A prefix of an array is a subarray that starts from the beginning of the array and extends to any point within it.
A suffix of an array is a subarray that starts at any point within the array and extends to the end of the array.
Note that the prefix and suffix to be chosen for the operation can be empty.
Note that x-value has a different definition in this version.
Example 1
|
|
Example 2
|
|
Example 3
|
|
Constraints
1 <= nums[i] <= 10^9
1 <= nums.length <= 10^5
1 <= k <= 5
1 <= queries.length <= 2 * 10^4
queries[i] == [indexi, valuei, starti, xi]
0 <= indexi <= nums.length - 1
1 <= valuei <= 10^9
0 <= starti <= nums.length - 1
0 <= xi <= k - 1
Examples
Solution
Method 1 – Prefix Product Modulo Counting (Brute-force for Small k)
Intuition
Since k is small (≤5), for each query, we can update the array, then for the required prefix, count the number of suffixes such that the product of the remaining subarray modulo k equals xi.
Approach
- For each query:
- Update nums[indexi] to valuei.
- For the subarray nums[starti:]:
- For each possible suffix (from starti to n-1), compute the product modulo k.
- For each possible subarray nums[starti:j+1], compute the product and count if it matches xi.
- Store the count for this query.
- Return the result array.
Code
|
|
|
|
Complexity
- ⏰ Time complexity:
O(Q * n^2)
, where Q is the number of queries and n is the array length. This is only feasible for small n and k. For large n, further optimizations (like segment trees or prefix product caching) are needed. - 🧺 Space complexity:
O(1)
(excluding output), as we only use a few counters.