Program to find out the sum of evenly spaced elements in an array in Python

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

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

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

  • for each value b, k in Q, do

    • if k

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

    • otherwise

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

Example

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 

Input

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

Output

[13, 9, 8]
Updated on: 2021-10-08T07:33:29+05:30

400 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements