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.
This problem requires calculating x-values by counting prefix products with specific remainders modulo k. The brute force approach processes each query independently with O(q × n) complexity. The smart caching approach uses modular arithmetic to prevent overflow and cache intermediate results. The binary search optimization can improve search performance when remainder sequences have predictable patterns, though preprocessing still requires O(n) time per query.
Common Approaches
✓
Binary Search Optimization
⏱️ Time: O(q × n)
Space: O(n)
This advanced approach recognizes that for certain patterns in the remainder sequence, binary search can be applied to find matching positions more efficiently than linear scanning, especially when the remainder sequence has predictable properties.
Brute Force Recipe Testing
⏱️ Time: O(q × n)
Space: O(1)
This approach directly implements the problem requirements by updating the array for each query, extracting the relevant subarray starting from the given index, then iterating through all possible prefixes to count how many have products with the target remainder modulo k.
Smart Recipe Caching
⏱️ Time: O(q × n)
Space: O(n)
This optimized approach maintains a cache of prefix products modulo k to avoid recalculating products from scratch for each query. It uses the fact that we only need remainders modulo k, not the actual products, which prevents overflow issues.
Binary Search Optimization — Algorithm Steps
Build prefix product remainders array for current query range
Identify if remainder sequence has searchable patterns
Apply binary search to locate positions with target remainder x
Count total occurrences using search boundaries
Visualization
Tap to expand
Step-by-Step Walkthrough
1
Build Sequence
Create remainder sequence from prefix products
2
Search Pattern
Identify searchable patterns in remainders
3
Binary Search
Apply binary search to locate target values
4
Count Results
Count all occurrences efficiently
Code -
solution.c — C
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
// Parse array from string like "[1,2,3,4]"
int parse_array(char* str, int* arr) {
int count = 0;
char* ptr = str;
// Skip initial '['
while (*ptr && *ptr != '[') ptr++;
if (*ptr) ptr++;
while (*ptr) {
// Skip whitespace and commas
while (*ptr && (*ptr == ' ' || *ptr == ',' || *ptr == '\n' || *ptr == '\r')) ptr++;
if (*ptr == ']' || *ptr == '\0') break;
// Parse number
char* endptr;
long val = strtol(ptr, &endptr, 10);
if (endptr != ptr) {
arr[count++] = (int)val;
ptr = endptr;
} else {
ptr++;
}
}
return count;
}
// Parse 2D array from string like "[[0,2,1,2]]"
int parse_queries(char* str, int queries[][4]) {
int query_count = 0;
char* ptr = str;
// Skip initial '['
while (*ptr && *ptr != '[') ptr++;
if (*ptr) ptr++;
while (*ptr) {
// Look for start of inner array
while (*ptr && *ptr != '[') {
if (*ptr == ']') return query_count;
ptr++;
}
if (*ptr != '[') break;
ptr++; // skip '['
// Parse 4 numbers in this query
for (int i = 0; i < 4; i++) {
// Skip whitespace and commas
while (*ptr && (*ptr == ' ' || *ptr == ',' || *ptr == '\n' || *ptr == '\r')) ptr++;
char* endptr;
long val = strtol(ptr, &endptr, 10);
if (endptr != ptr) {
queries[query_count][i] = (int)val;
ptr = endptr;
}
}
// Skip to end of inner array
while (*ptr && *ptr != ']') ptr++;
if (*ptr) ptr++; // skip ']'
query_count++;
}
return query_count;
}
char* solution() {
static char line[100000];
static int nums[1000];
static int queries[1000][4];
static char result[10000];
// Read nums
fgets(line, sizeof(line), stdin);
int nums_size = parse_array(line, nums);
// Read k
fgets(line, sizeof(line), stdin);
int k = atoi(line);
// Read queries
fgets(line, sizeof(line), stdin);
int queries_size = parse_queries(line, queries);
strcpy(result, "[");
for (int q = 0; q < queries_size; q++) {
int index = queries[q][0];
int value = queries[q][1];
int start = queries[q][2];
int x = queries[q][3];
// Update the array
nums[index] = value;
// Count occurrences of target x
int count = 0;
long long product = 1;
for (int i = start; i < nums_size; i++) {
product = (product * nums[i]) % k;
if (product == x) {
count++;
}
}
char num_str[20];
sprintf(num_str, "%d", count);
strcat(result, num_str);
if (q < queries_size - 1) {
strcat(result, ",");
}
}
strcat(result, "]");
return result;
}
int main() {
char *result = solution();
printf("%s\n", result);
return 0;
}
Time & Space Complexity
Time Complexity
⏱️
O(q × n)
Still O(n) per query due to preprocessing, but individual searches can be O(log n)
n
2n
✓ Linear Growth
Space Complexity
O(n)
Space for remainder sequence and search structures
n
2n
⚡ Linearithmic Space
12.8K Views
MediumFrequency
~35 minAvg. Time
420 Likes
Ln 1, Col 1
Smart Actions
💡Explanation
AI Ready
💡 SuggestionTabto acceptEscto dismiss
// Output will appear here after running code
Code Editor Closed
Click the red button to reopen
Algorithm Visualization
Pinch to zoom • Tap outside to close
Test Cases
0 passed
0 failed
3 pending
Select Compiler
Choose a programming language
Compiler list would appear here...
AI Editor Features
Header Buttons
💡
Explain
Get a detailed explanation of your code. Select specific code or analyze the entire file. Understand algorithms, logic flow, and complexity.
🔧
Fix
Automatically detect and fix issues in your code. Finds bugs, syntax errors, and common mistakes. Shows you what was fixed.
💡
Suggest
Get improvement suggestions for your code. Best practices, performance tips, and code quality recommendations.
💬
Ask AI
Open an AI chat assistant to ask any coding questions. Have a conversation about your code, get help with debugging, or learn new concepts.
Smart Actions (Slash Commands)
🔧
/fix Enter
Find and fix issues in your code. Detects common problems and applies automatic fixes.
💡
/explain Enter
Get a detailed explanation of what your code does, including time/space complexity analysis.
🧪
/tests Enter
Automatically generate unit tests for your code. Creates comprehensive test cases.
📝
/docs Enter
Generate documentation for your code. Creates docstrings, JSDoc comments, and type hints.
⚡
/optimize Enter
Get performance optimization suggestions. Improve speed and reduce memory usage.
AI Code Completion (Copilot-style)
👻
Ghost Text Suggestions
As you type, AI suggests code completions shown in gray text. Works with keywords like def, for, if, etc.
Tabto acceptEscto dismiss
💬
Comment-to-Code
Write a comment describing what you want, and AI generates the code. Try: # two sum, # binary search, # fibonacci
💡
Pro Tip: Select specific code before using Explain, Fix, or Smart Actions to analyze only that portion. Otherwise, the entire file will be analyzed.