Sum Of Special Evenly-Spaced Elements In Array Problem
Description
LeetCode Problem 1714.
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] = [x_i, y_i]. The answer to the i^th query is the sum of all nums[j] where x_i <= j < n and (j - x_i) is divisible by y_i.
Return an array answer where answer.length == queries.length and answer[i] is the answer to the i^th query modulo 10^9+ 7.
Example 1:
Input: nums = [0,1,2,3,4,5,6,7], queries = [[0,3],[5,1],[4,2]]
Output: [9,18,10]
Explanation: The answers of the queries are as follows:
1) The j indices that satisfy this query are 0, 3, and 6. nums[0] + nums[3] + nums[6] = 9
2) The j indices that satisfy this query are 5, 6, and 7. nums[5] + nums[6] + nums[7] = 18
3) The j indices that satisfy this query are 4 and 6. nums[4] + nums[6] = 10
Example 2:
Input: nums = [100,200,101,201,102,202,103,203], queries = [[0,7]]
Output: [303]
Constraints:
n == nums.length1 <= n <= 5 * 10^40 <= nums[i] <= 10^91 <= queries.length <= 1.5 * 10^50 <= x_i < n1 <= y_i <= 5 * 10^4
Solution
Approach: Square Root Decomposition
A query with a large step y touches only a few elements, so we can sum them directly. A query with a small step may touch many elements, so we precompute those answers.
Let m = floor(sqrt(n)). For every step i from 1 to m, compute the suffix sums suf[i][j] = nums[j] + suf[i][j + i] (modulo 10^9 + 7), going from the end of the array. Then for a query [x, y]:
- if
y <= m, the answer issuf[y][x]; - otherwise, add up
nums[x], nums[x + y], ...directly, which takes fewer thansqrt(n)steps.
Complexity: O((n + q) sqrt(n)) time and O(n sqrt(n)) space, where n is the length of the array and q the number of queries.
from math import sqrt
class Solution:
def solve(self, nums: List[int], queries: List[List[int]]) -> List[int]:
mod = 10**9 + 7
n = len(nums)
m = int(sqrt(n))
suf = [[0] * (n + 1) for _ in range(m + 1)]
for i in range(1, m + 1):
for j in range(n - 1, -1, -1):
suf[i][j] = suf[i][min(n, j + i)] + nums[j]
ans = []
for x, y in queries:
if y <= m:
ans.append(suf[y][x] % mod)
else:
ans.append(sum(nums[x::y]) % mod)
return ans