Problem
You are given an array of positive integers nums
, and a positive integer k
.
You are allowed to perform an operation once on nums
, where in each operation you can remove any non-overlapping prefix and suffix from nums
such that nums
remains non-empty.
You need to find the x-value of nums
, which is the number of ways to perform this operation so that the product of the remaining elements leaves a remainder of x
when divided by k
.
Return an array result
of size k
where result[x]
is the x-value of
nums
for 0 <= x <= k - 1
.
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.
Example 1
|
|
Example 2
|
|
Example 3
|
|
Constraints
1 <= nums[i] <= 10^9
1 <= nums.length <= 10^5
1 <= k <= 5
Examples
Solution
Method 1 – Prefix/Suffix Product Modulo Counting
Intuition
Since k is small (≤5), we can precompute prefix and suffix products modulo k. For each possible subarray (after removing a prefix and a suffix), we count the number of ways the product modulo k is x for each x in 0..k-1.
Approach
- Compute prefix products modulo k for all positions.
- Compute suffix products modulo k for all positions.
- For each possible subarray (from i to j), the product is:
- prefix_prod[i-1]^{-1} * suffix_prod[j+1]^{-1} * total_prod (all mod k)
- But since k is small, we can brute-force all possible (l, r) pairs (remove prefix of length l and suffix of length r, with l + r < n).
- For each remaining subarray, compute its product modulo k and increment the count for that x.
- Return the result array.
Code
|
|
|
|
|
|
Complexity
- ⏰ Time complexity:
O(n^3)
, but since k is small and n is up to 1e5, this brute-force is only feasible for small n. For larger n, further optimizations are needed, but for k ≤ 5 and small n, this works. - 🧺 Space complexity:
O(k)
, for the result array.