Open In App

Sum of elements in given range from Array formed by infinitely concatenating given array

Last Updated : 03 Aug, 2021
Comments
Improve
Suggest changes
Like Article
Like
Report

Given an array arr[](1-based indexing) consisting of N positive integers and two positive integers L and R,  the task is to find the sum of array elements over the range [L, R] if the given array arr[] is concatenating to itself infinite times.

Examples:

Input: arr[] = {1, 2, 3}, L = 2, R = 8
Output: 14
Explanation:
The array, arr[] after concatenation is {1, 2, 3, 1, 2, 3, 1, 2, ...} and the sum of elements from index 2 to 8 is 2 + 3 + 1 + 2 + 3 + 1 + 2 = 14.

Input: arr[] = {5, 2, 6, 9}, L = 10, R = 13
Output: 22

Naive Approach: The simplest approach to solve the given problem is to iterate over the range [L, R] using the variable i and add the value of arr[i % N] to the sum for each index. After completing the iteration, print the value of the sum as the resultant sum.

Below is the implementation of the above approach:

C++
Java Python3 C# JavaScript

Output: 
22

 

Time Complexity: O(R - L) 
Auxiliary Space: O(1)

Efficient Approach: The above approach can also be optimized by using the Prefix Sum. Follow the steps below to solve the problem:

  • Initialize an array, say prefix[] of size (N + 1) with all elements as 0s.
  • Traverse the array, arr[] using the variable i and update prefix[i] to sum of prefix[i - 1] and arr[i - 1].
  • Now, the sum of elements over the range [L, R] is given by:

the sum of elements in the range [1, R] - sum of elements in the range [1, L - 1].

  • Initialize a variable, say leftSum as ((L - 1)/N)*prefix[N] + prefix[(L - 1)%N] to store the sum of elements in the range [1, L-1].
  • Similarly, initialize another variable rightSum as (R/N)*prefix[N] + prefix[R%N] to store the sum of elements in the range [1, R].
  • After completing the above steps, print the value of (rightSum - leftSum) as the resultant sum of elements over the given range [L, R].

Below is the implementation of the above approach:

C++
Java Python3 C# JavaScript

Output: 
22

 

Time Complexity: O(N)
Auxiliary Space: O(N)


Next Article

Similar Reads