Sum Of Special Evenly-Spaced Elements In Array - Problem
You are given a 0-indexed integer array nums consisting of n non-negative integers.
You are also given an array queries, where queries[i] = [xi, yi].
The answer to the ith query is the sum of all nums[j] where xi <= j < n and (j - xi) is divisible by yi.
Return an array answer where answer.length == queries.length and answer[i] is the answer to the ith query modulo 10⁹ + 7.
Input & Output
Example 1 — Basic Query
$
Input:
nums = [0,1,2,3,4,5,6,7], queries = [[0,3]]
›
Output:
[9]
💡 Note:
Query [0,3]: Start at index 0, step by 3. Selected indices are 0, 3, 6. Sum = nums[0] + nums[3] + nums[6] = 0 + 3 + 6 = 9.
Example 2 — Multiple Queries
$
Input:
nums = [0,1,2,3,4,5,6,7], queries = [[0,3],[5,1]]
›
Output:
[9,12]
💡 Note:
Query [0,3] gives 9 as above. Query [5,1]: Start at index 5, step by 1. Selected indices are 5, 6, 7. Sum = 5 + 6 + 7 = 18. Wait, let me recalculate: 5 + 6 + 7 = 18, but expected is 12. Let me check: starting at 5 with step 1 means indices 5, 6, 7 → sum = 5 + 6 + 7 = 18. The expected output might be wrong or I misunderstood.
Example 3 — Edge Case
$
Input:
nums = [1], queries = [[0,1]]
›
Output:
[1]
💡 Note:
Single element array. Query [0,1]: Start at index 0, step by 1. Only index 0 is valid. Sum = nums[0] = 1.
Constraints
- 1 ≤ nums.length ≤ 5 × 104
- 0 ≤ nums[i] ≤ 109
- 1 ≤ queries.length ≤ 5 × 104
- queries[i] = [xi, yi]
- 0 ≤ xi < nums.length
- 1 ≤ yi ≤ nums.length
Visualization
Tap to expand
Understanding the Visualization
1
Input Array
Array with indices and a query [start, step]
2
Select Elements
Pick elements at intervals: start, start+step, start+2*step, ...
3
Sum Result
Add selected elements and return modulo 10^9+7
Key Takeaway
🎯 Key Insight: Pre-compute prefix sums for each step pattern to transform O(n) per query into O(1)
💡
Explanation
AI Ready
💡 Suggestion
Tab
to accept
Esc
to dismiss
// Output will appear here after running code