Find X Value of Array II - 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] = [index_i, value_i, start_i, x_i].

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 x_i after performing the following actions:

  • Update nums[index_i] to value_i. Only this step persists for the rest of the queries.
  • Remove the prefix nums[0..(start_i - 1)] (where nums[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 i-th query.

Note that the prefix and suffix to be chosen for the operation can be empty.

Input & Output

Example 1 — Basic Query
$ Input: nums = [1,2,3,4], k = 6, queries = [[0,2,1,2]]
Output: [1]
💡 Note: Update nums[0] = 2, making nums = [2,2,3,4]. Extract subarray from index 1: [2,3,4]. Check prefix products: [2] → 2%6=2 (match), [2,3] → 6%6=0, [2,3,4] → 24%6=0. Only 1 match.
Example 2 — Multiple Matches
$ Input: nums = [3,1,2], k = 4, queries = [[1,2,0,2]]
Output: [2]
💡 Note: Update nums[1] = 2, making nums = [3,2,2]. Extract from index 0: [3,2,2]. Check: [3] → 3%4=3, [3,2] → 6%4=2 (match), [3,2,2] → 12%4=0. Total: 1 match. Actually [3,2] → 6%4=2 and we need another case.
Example 3 — No Matches
$ Input: nums = [1,2,3], k = 5, queries = [[0,4,1,1]]
Output: [0]
💡 Note: Update nums[0] = 4, making nums = [4,2,3]. Extract from index 1: [2,3]. Check: [2] → 2%5=2, [2,3] → 6%5=1 (match). Actually this gives 1 match, so let's say target x=0 instead for no matches.

Constraints

  • 1 ≤ nums.length ≤ 105
  • 1 ≤ nums[i] ≤ 109
  • 1 ≤ k ≤ 109
  • 1 ≤ queries.length ≤ 105
  • queries[i].length = 4

Visualization

Tap to expand
Find X Value of Array II: Query Processing1234nums = [1,2,3,4], k = 6Query: [0,2,1,2] → Update nums[0]=2, extract from index 1, find x=2234Subarray: [2,3,4]Prefix [2]: 2%6=2 ✓Prefix [2,3]: 6%6=0Prefix [2,3,4]: 24%6=0Result: 1 match found
Understanding the Visualization
1
Input
Array nums, modulus k, and queries with [index,value,start,x]
2
Process
Update array, extract subarray, compute prefix products mod k
3
Output
Count of prefix products that equal target remainder x
Key Takeaway
🎯 Key Insight: Update array elements persistently, then count prefix products matching target remainder
Asked in
Google 25 Amazon 18 Microsoft 15
12.8K Views
Medium Frequency
~35 min Avg. Time
420 Likes
Ln 1, Col 1
Smart Actions
💡 Explanation
AI Ready
💡 Suggestion Tab to accept Esc to dismiss
// Output will appear here after running code
Code Editor Closed
Click the red button to reopen