Sum Of Special Evenly-Spaced Elements In Array — LeetCode 1714 Python Solution

HardLeetCode PremiumArrayDynamic Programming
Problem
#1714
Reading time
3 min

The 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].

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:

Python solution

Python
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

MeasureComplexity
TimeO((n + m) \times \sqrt{n})
SpaceO(n \times \sqrt{n}) auxiliary

Pattern: Dynamic Programming

Define a state, write the transition, and stop recomputing the same subproblem. LeetCode 1714. Sum Of Special Evenly-Spaced Elements In Array is filed here on both counts: the reference solution below belongs to the algorithm family this hub collects, and LeetCode tags it Dynamic Programming.

The dynamic programming guide has the Python template for the pattern and the 481 LeetCode problems that use it.

Related problems

Frequently asked questions

How hard is LeetCode 1714. Sum Of Special Evenly-Spaced Elements In Array?
LeetCode 1714. Sum Of Special Evenly-Spaced Elements In Array is rated Hard on LeetCode.
What is the time complexity of LeetCode 1714. Sum Of Special Evenly-Spaced Elements In Array?
The Python solution on this page runs in O((n + m) \times \sqrt{n}).
What is the space complexity of LeetCode 1714. Sum Of Special Evenly-Spaced Elements In Array?
The Python solution on this page uses O(n \times \sqrt{n}) auxiliary space.
What topics does LeetCode 1714. Sum Of Special Evenly-Spaced Elements In Array cover?
LeetCode 1714. Sum Of Special Evenly-Spaced Elements In Array is tagged Array and Dynamic Programming on LeetCode.
Is LeetCode 1714. Sum Of Special Evenly-Spaced Elements In Array a premium problem?
Yes. LeetCode 1714. Sum Of Special Evenly-Spaced Elements In Array is a LeetCode Premium problem, so the full statement and test cases require a paid LeetCode subscription.

Stuck on problems like this in a live interview?

Stealth Interview is a desktop app for macOS and Windows. It reads the problem off your screen and returns a working solution with a step-by-step explanation and its time and space complexity — invisible to screen sharing.

Get Stealth Interview