Sum of elements in given range from Array formed by infinitely concatenating given array
Last Updated :
23 Jul, 2025
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++
// C++ program for the above approach
#include <bits/stdc++.h>
using namespace std;
// Function to find the sum of elements
// in a given range of an infinite array
void rangeSum(int arr[], int N, int L, int R)
{
// Stores the sum of array elements
// from L to R
int sum = 0;
// Traverse from L to R
for (int i = L - 1; i < R; i++) {
sum += arr[i % N];
}
// Print the resultant sum
cout << sum;
}
// Driver Code
int main()
{
int arr[] = { 5, 2, 6, 9 };
int L = 10, R = 13;
int N = sizeof(arr) / sizeof(arr[0]);
rangeSum(arr, N, L, R);
return 0;
}
Java
// Java program for the above approach
import java.io.*;
class GFG
{
// Function to find the sum of elements
// in a given range of an infinite array
static void rangeSum(int arr[], int N, int L, int R)
{
// Stores the sum of array elements
// from L to R
int sum = 0;
// Traverse from L to R
for (int i = L - 1; i < R; i++) {
sum += arr[i % N];
}
// Print the resultant sum
System.out.println(sum);
}
// Driver Code
public static void main(String[] args)
{
int arr[] = { 5, 2, 6, 9 };
int L = 10, R = 13;
int N = arr.length;
rangeSum(arr, N, L, R);
}
}
// This code is contributed by Potta Lokesh
Python3
# Python 3 program for the above approach
# Function to find the sum of elements
# in a given range of an infinite array
def rangeSum(arr, N, L, R):
# Stores the sum of array elements
# from L to R
sum = 0
# Traverse from L to R
for i in range(L - 1,R,1):
sum += arr[i % N]
# Print the resultant sum
print(sum)
# Driver Code
if __name__ == '__main__':
arr = [5, 2, 6, 9 ]
L = 10
R = 13
N = len(arr)
rangeSum(arr, N, L, R)
# This code is contributed by divyeshrabadiya07
C#
// C# program for the above approach
using System;
class GFG {
// Function to find the sum of elements
// in a given range of an infinite array
static void rangeSum(int[] arr, int N, int L, int R)
{
// Stores the sum of array elements
// from L to R
int sum = 0;
// Traverse from L to R
for (int i = L - 1; i < R; i++) {
sum += arr[i % N];
}
// Print the resultant sum
Console.Write(sum);
}
// Driver Code
public static void Main(string[] args)
{
int[] arr = { 5, 2, 6, 9 };
int L = 10, R = 13;
int N = arr.Length;
rangeSum(arr, N, L, R);
}
}
// This code is contributed by ukasp.
JavaScript
<script>
// Javascript program for the above approach
// Function to find the sum of elements
// in a given range of an infinite array
function rangeSum(arr, N, L, R)
{
// Stores the sum of array elements
// from L to R
let sum = 0;
// Traverse from L to R
for(let i = L - 1; i < R; i++)
{
sum += arr[i % N];
}
// Print the resultant sum
document.write(sum);
}
// Driver Code
let arr = [ 5, 2, 6, 9 ];
let L = 10, R = 13;
let N = arr.length
rangeSum(arr, N, L, R);
// This code is contributed by _saurabh_jaiswal
</script>
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++
// C++ program for the above approach
#include <bits/stdc++.h>
using namespace std;
// Function to find the sum of elements
// in a given range of an infinite array
void rangeSum(int arr[], int N, int L,
int R)
{
// Stores the prefix sum
int prefix[N + 1];
prefix[0] = 0;
// Calculate the prefix sum
for (int i = 1; i <= N; i++) {
prefix[i] = prefix[i - 1]
+ arr[i - 1];
}
// Stores the sum of elements
// from 1 to L-1
int leftsum
= ((L - 1) / N) * prefix[N]
+ prefix[(L - 1) % N];
// Stores the sum of elements
// from 1 to R
int rightsum = (R / N) * prefix[N]
+ prefix[R % N];
// Print the resultant sum
cout << rightsum - leftsum;
}
// Driver Code
int main()
{
int arr[] = { 5, 2, 6, 9 };
int L = 10, R = 13;
int N = sizeof(arr) / sizeof(arr[0]);
rangeSum(arr, N, L, R);
return 0;
}
Java
// Java program for the above approach
import java.io.*;
class GFG{
// Function to find the sum of elements
// in a given range of an infinite array
static void rangeSum(int arr[], int N, int L, int R)
{
// Stores the prefix sum
int prefix[] = new int[N+1];
prefix[0] = 0;
// Calculate the prefix sum
for (int i = 1; i <= N; i++) {
prefix[i] = prefix[i - 1]
+ arr[i - 1];
}
// Stores the sum of elements
// from 1 to L-1
int leftsum
= ((L - 1) / N) * prefix[N]
+ prefix[(L - 1) % N];
// Stores the sum of elements
// from 1 to R
int rightsum = (R / N) * prefix[N]
+ prefix[R % N];
// Print the resultant sum
System.out.print( rightsum - leftsum);
}
// Driver Code
public static void main (String[] args)
{
int arr[] = { 5, 2, 6, 9 };
int L = 10, R = 13;
int N = arr.length;
rangeSum(arr, N, L, R);
}
}
// This code is contributed by shivanisinghss2110
Python3
# Python 3 program for the above approach
# Function to find the sum of elements
# in a given range of an infinite array
def rangeSum(arr, N, L, R):
# Stores the prefix sum
prefix = [0 for i in range(N + 1)]
prefix[0] = 0
# Calculate the prefix sum
for i in range(1,N+1,1):
prefix[i] = prefix[i - 1] + arr[i - 1]
# Stores the sum of elements
# from 1 to L-1
leftsum = ((L - 1) // N) * prefix[N] + prefix[(L - 1) % N]
# Stores the sum of elements
# from 1 to R
rightsum = (R // N) * prefix[N] + prefix[R % N]
# Print the resultant sum
print(rightsum - leftsum)
# Driver Code
if __name__ == '__main__':
arr = [5, 2, 6, 9]
L = 10
R = 13
N = len(arr)
rangeSum(arr, N, L, R)
# This code is contributed by SURENDRA_GANGWAR.
C#
// C# program for the above approach
using System;
class GFG{
// Function to find the sum of elements
// in a given range of an infinite array
static void rangeSum(int []arr, int N, int L, int R)
{
// Stores the prefix sum
int []prefix = new int[N+1];
prefix[0] = 0;
// Calculate the prefix sum
for (int i = 1; i <= N; i++) {
prefix[i] = prefix[i - 1]
+ arr[i - 1];
}
// Stores the sum of elements
// from 1 to L-1
int leftsum
= ((L - 1) / N) * prefix[N]
+ prefix[(L - 1) % N];
// Stores the sum of elements
// from 1 to R
int rightsum = (R / N) * prefix[N]
+ prefix[R % N];
// Print the resultant sum
Console.Write( rightsum - leftsum);
}
// Driver Code
public static void Main (String[] args)
{
int []arr = { 5, 2, 6, 9 };
int L = 10, R = 13;
int N = arr.Length;
rangeSum(arr, N, L, R);
}
}
// This code is contributed by shivanisinghss2110
JavaScript
<script>
// JavaScript program for the above approach
// Function to find the sum of elements
// in a given range of an infinite array
function rangeSum(arr, N, L, R) {
// Stores the prefix sum
let prefix = new Array(N + 1);
prefix[0] = 0;
// Calculate the prefix sum
for (let i = 1; i <= N; i++) {
prefix[i] = prefix[i - 1] + arr[i - 1];
}
// Stores the sum of elements
// from 1 to L-1
let leftsum = ((L - 1) / N) * prefix[N] + prefix[(L - 1) % N];
// Stores the sum of elements
// from 1 to R
let rightsum = (R / N) * prefix[N] + prefix[R % N];
// Print the resultant sum
document.write(rightsum - leftsum);
}
// Driver Code
let arr = [5, 2, 6, 9];
let L = 10,
R = 13;
let N = arr.length;
rangeSum(arr, N, L, R);
</script>
Time Complexity: O(N)
Auxiliary Space: O(N)
Similar Reads
Basics & Prerequisites
Data Structures
Array Data StructureIn this article, we introduce array, implementation in different popular languages, its basic operations and commonly seen problems / interview questions. An array stores items (in case of C/C++ and Java Primitive Arrays) or their references (in case of Python, JS, Java Non-Primitive) at contiguous
3 min read
String in Data StructureA string is a sequence of characters. The following facts make string an interesting data structure.Small set of elements. Unlike normal array, strings typically have smaller set of items. For example, lowercase English alphabet has only 26 characters. ASCII has only 256 characters.Strings are immut
2 min read
Hashing in Data StructureHashing is a technique used in data structures that efficiently stores and retrieves data in a way that allows for quick access. Hashing involves mapping data to a specific index in a hash table (an array of items) using a hash function. It enables fast retrieval of information based on its key. The
2 min read
Linked List Data StructureA linked list is a fundamental data structure in computer science. It mainly allows efficient insertion and deletion operations compared to arrays. Like arrays, it is also used to implement other data structures like stack, queue and deque. Hereâs the comparison of Linked List vs Arrays Linked List:
2 min read
Stack Data StructureA Stack is a linear data structure that follows a particular order in which the operations are performed. The order may be LIFO(Last In First Out) or FILO(First In Last Out). LIFO implies that the element that is inserted last, comes out first and FILO implies that the element that is inserted first
2 min read
Queue Data StructureA Queue Data Structure is a fundamental concept in computer science used for storing and managing data in a specific order. It follows the principle of "First in, First out" (FIFO), where the first element added to the queue is the first one to be removed. It is used as a buffer in computer systems
2 min read
Tree Data StructureTree Data Structure is a non-linear data structure in which a collection of elements known as nodes are connected to each other via edges such that there exists exactly one path between any two nodes. Types of TreeBinary Tree : Every node has at most two childrenTernary Tree : Every node has at most
4 min read
Graph Data StructureGraph Data Structure is a collection of nodes connected by edges. It's used to represent relationships between different entities. If you are looking for topic-wise list of problems on different topics like DFS, BFS, Topological Sort, Shortest Path, etc., please refer to Graph Algorithms. Basics of
3 min read
Trie Data StructureThe Trie data structure is a tree-like structure used for storing a dynamic set of strings. It allows for efficient retrieval and storage of keys, making it highly effective in handling large datasets. Trie supports operations such as insertion, search, deletion of keys, and prefix searches. In this
15+ min read
Algorithms
Searching AlgorithmsSearching algorithms are essential tools in computer science used to locate specific items within a collection of data. In this tutorial, we are mainly going to focus upon searching in an array. When we search an item in an array, there are two most common algorithms used based on the type of input
2 min read
Sorting AlgorithmsA Sorting Algorithm is used to rearrange a given array or list of elements in an order. For example, a given array [10, 20, 5, 2] becomes [2, 5, 10, 20] after sorting in increasing order and becomes [20, 10, 5, 2] after sorting in decreasing order. There exist different sorting algorithms for differ
3 min read
Introduction to RecursionThe process in which a function calls itself directly or indirectly is called recursion and the corresponding function is called a recursive function. A recursive algorithm takes one step toward solution and then recursively call itself to further move. The algorithm stops once we reach the solution
14 min read
Greedy AlgorithmsGreedy algorithms are a class of algorithms that make locally optimal choices at each step with the hope of finding a global optimum solution. At every step of the algorithm, we make a choice that looks the best at the moment. To make the choice, we sometimes sort the array so that we can always get
3 min read
Graph AlgorithmsGraph is a non-linear data structure like tree data structure. The limitation of tree is, it can only represent hierarchical data. For situations where nodes or vertices are randomly connected with each other other, we use Graph. Example situations where we use graph data structure are, a social net
3 min read
Dynamic Programming or DPDynamic Programming is an algorithmic technique with the following properties.It is mainly an optimization over plain recursion. Wherever we see a recursive solution that has repeated calls for the same inputs, we can optimize it using Dynamic Programming. The idea is to simply store the results of
3 min read
Bitwise AlgorithmsBitwise algorithms in Data Structures and Algorithms (DSA) involve manipulating individual bits of binary representations of numbers to perform operations efficiently. These algorithms utilize bitwise operators like AND, OR, XOR, NOT, Left Shift, and Right Shift.BasicsIntroduction to Bitwise Algorit
4 min read
Advanced
Segment TreeSegment Tree is a data structure that allows efficient querying and updating of intervals or segments of an array. It is particularly useful for problems involving range queries, such as finding the sum, minimum, maximum, or any other operation over a specific range of elements in an array. The tree
3 min read
Pattern SearchingPattern searching algorithms are essential tools in computer science and data processing. These algorithms are designed to efficiently find a particular pattern within a larger set of data. Patten SearchingImportant Pattern Searching Algorithms:Naive String Matching : A Simple Algorithm that works i
2 min read
GeometryGeometry is a branch of mathematics that studies the properties, measurements, and relationships of points, lines, angles, surfaces, and solids. From basic lines and angles to complex structures, it helps us understand the world around us.Geometry for Students and BeginnersThis section covers key br
2 min read
Interview Preparation
Practice Problem