Leetcode #1714: Sum Of Special Evenly-Spaced Elements In Array
In this guide, we solve Leetcode #1714 Sum Of Special Evenly-Spaced Elements In Array in Python and focus on the core idea that makes the solution efficient.
You will see the intuition, the step-by-step method, and a clean Python implementation you can use in interviews.

Problem Statement
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].
Quick Facts
- Difficulty: Hard
- Premium: Yes
- Tags: Array, Dynamic Programming
Intuition
The problem breaks into overlapping subproblems, so caching results prevents exponential repetition.
A carefully chosen DP state captures exactly what we need to build the final answer.
Approach
Define the DP state and recurrence, then compute states in the correct order.
Optionally compress space once the recurrence is clear.
Steps:
- Choose a DP state definition.
- Write the recurrence and base cases.
- Compute states in the correct order.
Example
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
Python Solution
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
Complexity
The time complexity is , and the space complexity is . The space complexity is .
Edge Cases and Pitfalls
Watch for boundary values, empty inputs, and duplicate values where applicable. If the problem involves ordering or constraints, confirm the invariant is preserved at every step.
Summary
This Python solution focuses on the essential structure of the problem and keeps the implementation interview-friendly while meeting the constraints.