- Trending Categories
- Data Structure
- Networking
- RDBMS
- Operating System
- Java
- iOS
- HTML
- CSS
- Android
- Python
- C Programming
- C++
- C#
- MongoDB
- MySQL
- Javascript
- PHP

- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who

Suppose, there is an array 'nums' of size n containing positive integers. We have another array 'queries' that contain integer pairs (pi, qi). For every query in the array queries, the answer will be the sum of numbers in the array nums[j] where pi <= j < n and (j - pi) is divisible by qi. We have to return the answer of all such queries, and if it is a large value, we return the answer modulo 10^9 + 7.

So, if the input is like nums = [2, 3, 4, 5, 6, 7, 8, 9, 10], queries = [(2, 5), (7, 3), (6, 4)], then the output will be [13, 9, 8].

To solve this, we will follow these steps −

A := nums

Q := queries

n := length of nums

M := 10^9 + 7

m := integer value of (n ^ 0.5) + 2

P := a new list containing the list A m times

for i in range 1 to m, do

for j in range n-1 to -1, decrease by 1, do

if i+j < n, then

P[i, j] := (P[i, j]+P[i, i+j]) modulo M

for each value b, k in Q, do

if k < m, then

return [value from index P[k, b]]

otherwise

return [sum(A[b to k]) modulo M]

Let us see the following implementation to get better understanding −

def solve(A, Q): n, M = len(A), 10**9+7 m = int(n**0.5)+2 P = [A[:] for _ in range(m)] for i in range(1,m): for j in range(n-1,-1,-1): if i+j < n: P[i][j] = (P[i][j]+P[i][i+j]) % M return [P[k][b] if k < m else sum(A[b::k]) % M for b, k in Q] print(solve([2, 3, 4, 5, 6, 7, 8, 9, 10], [(2, 5), (7, 3), (6, 4)]))

[2, 3, 4, 5, 6, 7, 8, 9, 10], [(2, 5), (7, 3), (6, 4)]

[13, 9, 8]

- Related Questions & Answers
- Java program to find the sum of elements of an array
- Find the sum of array in Python Program
- Python Program to find the sum of array
- Python Program to find out the sum of values in hyperrectangle cells
- Python program to find sum of elements in list
- Program to find sum of unique elements in Python
- Create an evenly spaced color stops with CSS Radial Gradients
- Program to find out the sum of the number of divisor of the divisors in Python
- C Program to find sum of perfect square elements in an array using pointers.
- Find sum of elements in list in Python program
- Program to Find Out Median of an Integer Array in C++
- C++ code to find out the sum of the special matrix elements
- How to find the sum of elements of an Array using STL in C++?
- C/C++ Program to find the sum of elements in a given array
- Program to Find Out the Largest K-Divisible Subsequence Sum in Python

Advertisements