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,2]]
Output: [9,12]
💡 Note: Query [0,3] gives 9 as above. Query [5,2]: Start at index 5, step by 2. Selected indices are 5, 7. Sum = 5 + 7 = 12.
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
Sum Of Special Evenly-Spaced Elements INPUT nums array (indices 0-7): 0 i=0 1 i=1 2 i=2 3 i=3 4 i=4 5 i=5 6 i=6 7 7 i=7 Query: [0, 3] x = 0 (start index) y = 3 (step size) Selected Indices: j = 0, 3, 6 (step by 3) (j-0) % 3 == 0 ALGORITHM STEPS 1 Parse Query x=0, y=3 from [0,3] 2 Find Valid Indices j where (j-x) % y == 0 3 Sum Elements Add nums[j] for valid j 4 Apply Modulo Result % (10^9 + 7) Calculation Details: j=0: (0-0)%3=0 OK nums[0]=0 j=3: (3-0)%3=0 OK nums[3]=3 j=6: (6-0)%3=0 OK nums[6]=6 Sum = 0 + 3 + 6 = 9 FINAL RESULT Output Array: [9] Verification: Query [0,3]: nums[0]+nums[3]+nums[6] = 0 + 3 + 6 = 9 OK - Correct! Evenly Spaced Pattern: 0 1 2 3 4 5 6 Key Insight: For optimal solution with large y values: iterate directly with step y from index x. For small y values: precompute suffix sums to avoid repeated calculations. Time Complexity: O(n * sqrt(n)) using threshold-based approach. Space: O(n * sqrt(n)) for precomputation. TutorialsPoint - Sum Of Special Evenly-Spaced Elements In Array | Optimal Solution
Asked in
Google 45 Amazon 38 Microsoft 32 Facebook 28
23.4K Views
Medium Frequency
~35 min Avg. Time
847 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