Skip to content
geeksforgeeks
  • Courses
    • DSA to Development
    • Get IBM Certification
    • Newly Launched!
      • Master Django Framework
      • Become AWS Certified
    • For Working Professionals
      • Interview 101: DSA & System Design
      • Data Science Training Program
      • JAVA Backend Development (Live)
      • DevOps Engineering (LIVE)
      • Data Structures & Algorithms in Python
    • For Students
      • Placement Preparation Course
      • Data Science (Live)
      • Data Structure & Algorithm-Self Paced (C++/JAVA)
      • Master Competitive Programming (Live)
      • Full Stack Development with React & Node JS (Live)
    • Full Stack Development
    • Data Science Program
    • All Courses
  • Tutorials
    • Data Structures & Algorithms
    • ML & Data Science
    • Interview Corner
    • Programming Languages
    • Web Development
    • CS Subjects
    • DevOps And Linux
    • School Learning
  • Practice
    • Build your AI Agent
    • GfG 160
    • Problem of the Day
    • Practice Coding Problems
    • GfG SDE Sheet
  • Contests
    • Accenture Hackathon (Ending Soon!)
    • GfG Weekly [Rated Contest]
    • Job-A-Thon Hiring Challenge
    • All Contests and Events
  • DSA
  • Interview Questions on Array
  • Practice Array
  • MCQs on Array
  • Tutorial on Array
  • Types of Arrays
  • Array Operations
  • Subarrays, Subsequences, Subsets
  • Reverse Array
  • Static Vs Arrays
  • Array Vs Linked List
  • Array | Range Queries
  • Advantages & Disadvantages
Open In App
Next Article:
Range Queries for Frequencies of array elements
Next article icon

Range sum queries without updates

Last Updated : 06 Mar, 2025
Comments
Improve
Suggest changes
Like Article
Like
Report

Given an array arr of integers of size n. We need to compute the sum of elements from index i to index j. The queries consisting of i and j index values will be executed multiple times.

Examples: 

Input : arr[] = {1, 2, 3, 4, 5}
i = 1, j = 3
i = 2, j = 4
Output : 9
12
Input : arr[] = {1, 2, 3, 4, 5}
i = 0, j = 4
i = 1, j = 2
Output : 15
5

[Naive Solution] – Simple Sum – O(n) for Every Query and O(1) Space

A Simple Solution is to compute the sum for every query.

C++14
// C++ program to find sum between two indexes #include <bits/stdc++.h> using namespace std;  // Function to compute sum in given range int rangeSum(const vector<int>& arr, int i, int j) {     int sum = 0;      // Compute sum from i to j     for (int k = i; k <= j; k++) {         sum += arr[k];     }      return sum; }  // Driver code int main() {     vector<int> arr = { 1, 2, 3, 4, 5 };     cout << rangeSum(arr, 1, 3) << endl;     cout << rangeSum(arr, 2, 4) << endl;     return 0; } 
Java
public class Main {          // Function to compute sum in given range     static int rangeSum(int[] arr, int i, int j) {         int sum = 0;          // Compute sum from i to j         for (int k = i; k <= j; k++) {             sum += arr[k];         }          return sum;     }      // Driver code     public static void main(String[] args) {         int[] arr = { 1, 2, 3, 4, 5 };         System.out.println(rangeSum(arr, 1, 3));         System.out.println(rangeSum(arr, 2, 4));     } } 
Python
# Python3 program to find sum between two indexes # when there is no update.  # Function to compute sum in given range def rangeSum(arr, i, j) :     sum = 0;      # Compute sum from i to j     for k in range(i, j + 1) :         sum += arr[k];              return sum;  # Driver code if __name__ == "__main__" :   arr = [ 1, 2, 3, 4, 5 ];   print(rangeSum(arr, 1, 3));   print(rangeSum(arr, 2, 4)); 
C#
using System;  public class RangeSumCalculator {     // Function to compute sum in the given range     public static int RangeSum(int[] arr, int i, int j)     {         int sum = 0;          // Compute sum from index i to j         for (int k = i; k <= j; k++)         {             sum += arr[k];         }          return sum;     }      public static void Main(string[] args)     {         int[] arr = { 1, 2, 3, 4, 5 };         Console.WriteLine(RangeSum(arr, 1, 3));         Console.WriteLine(RangeSum(arr, 2, 4));     } } 
JavaScript
function GFG(arr, i, j) {     let sum = 0;      // Compute sum from i to j     for (let k = i; k <= j; k++) {         sum += arr[k];     }     return sum; }  const arr = [ 1, 2, 3, 4, 5 ]; console.log(GFG(arr, 1, 3)); console.log(GFG(arr, 2, 4)); 


Output

9 12 

[Expected Solution] – Prefix Sum – O(1) for Every Query and O(n) Space

Follow the given steps to solve the problem:

  • Create the prefix sum array of the given input array
  • Now for every query (1-based indexing)
    • If L is greater than 1, then print prefixSum[R] – prefixSum[L-1]
    • else print prefixSum[R]
C++
#include <bits/stdc++.h> using namespace std;  void preCompute(vector<int>& arr, vector<int>& pre) {     pre[0] = arr[0];     for (int i = 1; i < arr.size(); i++)         pre[i] = arr[i] + pre[i - 1]; }  // Returns sum of elements in arr[i..j] // It is assumed that i <= j int rangeSum(int i, int j, const vector<int>& pre) {     if (i == 0)         return pre[j];      return pre[j] - pre[i - 1]; }  // Driver code int main() {     vector<int> arr = { 1, 2, 3, 4, 5 };     vector<int> pre(arr.size());        // Function call     preCompute(arr, pre);     cout << rangeSum(1, 3, pre) << endl;     cout << rangeSum(2, 4, pre) << endl;      return 0; } 
Java
// Java program to find sum between two indexes // when there is no update.  import java.util.*; import java.lang.*;  class GFG {     public static void preCompute(int arr[], int pre[])     {         pre[0] = arr[0];         for (int i = 1; i < arr.length; i++)             pre[i] = arr[i] + pre[i - 1];     }      // Returns sum of elements in arr[i..j]     // It is assumed that i <= j     public static int rangeSum(int i, int j, int pre[])     {         if (i == 0)             return pre[j];          return pre[j] - pre[i - 1];     }      // Driver code     public static void main(String[] args)     {         int arr[] = { 1, 2, 3, 4, 5 };         int pre[] = new int[arr.length];          preCompute(arr, pre);         System.out.println(rangeSum(1, 3, pre));         System.out.println(rangeSum(2, 4, pre));     } } 
Python
# Function to precompute the prefix sum  def pre_compute(arr):     pre = [0] * len(arr)     pre[0] = arr[0]     for i in range(1, len(arr)):         pre[i] = arr[i] + pre[i - 1]     return pre  # Returns sum of elements in arr[i..j] # It is assumed that i <= j def range_sum(i, j, pre):     if i == 0:         return pre[j]     return pre[j] - pre[i - 1]  # Driver code arr = [1, 2, 3, 4, 5] pre = pre_compute(arr) print(range_sum(1, 3, pre)) print(range_sum(2, 4, pre)) 
C#
// C# program to find sum between two indexes using System;  class GFG {     public static void PreCompute(int[] arr, int[] pre)     {         pre[0] = arr[0];         for (int i = 1; i < arr.Length; i++)             pre[i] = arr[i] + pre[i - 1];     }      // Returns sum of elements in arr[i..j]     // It is assumed that i <= j     public static int RangeSum(int i, int j, int[] pre)     {         if (i == 0)             return pre[j];          return pre[j] - pre[i - 1];     }      // Driver code     public static void Main(string[] args)     {         int[] arr = { 1, 2, 3, 4, 5 };         int[] pre = new int[arr.Length];          PreCompute(arr, pre);         Console.WriteLine(RangeSum(1, 3, pre));         Console.WriteLine(RangeSum(2, 4, pre));     } } 
JavaScript
// Function to precompute the prefix sum function preCompute(arr) {     let pre = new Array(arr.length).fill(0);     pre[0] = arr[0];     for (let i = 1; i < arr.length; i++) {         pre[i] = arr[i] + pre[i - 1];     }     return pre; }  // Returns sum of elements in arr[i..j] // It is assumed that i <= j function rangeSum(i, j, pre) {     if (i === 0) {         return pre[j];     }     return pre[j] - pre[i - 1]; }  // Driver code let arr = [1, 2, 3, 4, 5]; let pre = preCompute(arr); console.log(rangeSum(1, 3, pre)); console.log(rangeSum(2, 4, pre)); 

Output
9 12

Here time complexity of every range sum query is O(1) and the overall time complexity is O(n).

Auxiliary Space required = O(n), where n is the size of the given array.

The question becomes complicated when updates are also allowed. In such situations when using advanced data structures like Segment Tree or Binary Indexed Tree.



Next Article
Range Queries for Frequencies of array elements
https://media.geeksforgeeks.org/auth/avatar.png
GeeksforGeeks
Improve
Article Tags :
  • Arrays
  • DSA
  • array-range-queries
  • prefix-sum
Practice Tags :
  • Arrays
  • prefix-sum

Similar Reads

  • PreComputation Technique on Arrays
    Precomputation refers to the process of pre-calculating and storing the results of certain computations or data structures(array in this case) in advance, in order to speed up the execution time of a program. This can be useful in situations where the same calculations are needed multiple times, as
    15 min read
  • Queries for the product of first N factorials
    Given Q[] queries where each query consists of an integer N, the task is to find the product of first N factorials for each of the query. Since the result could be large, compute it modulo 109 + 7.Examples: Input: Q[] = {4, 5} Output: 288 34560 Query 1: 1! * 2! * 3! * 4! = 1 * 2 * 6 * 24 = 288 Query
    7 min read
  • Range sum queries without updates
    Given an array arr of integers of size n. We need to compute the sum of elements from index i to index j. The queries consisting of i and j index values will be executed multiple times. Examples: Input : arr[] = {1, 2, 3, 4, 5} i = 1, j = 3 i = 2, j = 4Output : 9 12 Input : arr[] = {1, 2, 3, 4, 5} i
    6 min read
  • Range Queries for Frequencies of array elements
    Given an array of n non-negative integers. The task is to find frequency of a particular element in the arbitrary range of array[]. The range is given as positions (not 0 based indexes) in array. There can be multiple queries of given type. Examples: Input : arr[] = {2, 8, 6, 9, 8, 6, 8, 2, 11}; lef
    13 min read
  • Count Primes in Ranges
    Given a 2d array queries[][] of size n, where each query queries[i] contain 2 elements [l, r], your task is to find the count of number of primes in inclusive range [l, r] Examples: Input: queries[][] = [ [1, 10], [5, 10], [11, 20] ]Output: 4 2 4Explanation: For query 1, number of primes in range [1
    12 min read
  • Check in binary array the number represented by a subarray is odd or even
    Given an array such that all its terms is either 0 or 1.You need to tell the number represented by a subarray a[l..r] is odd or even Examples : Input : arr = {1, 1, 0, 1} l = 1, r = 3 Output : odd number represented by arr[l...r] is 101 which 5 in decimal form which is odd Input : arr = {1, 1, 1, 1}
    4 min read
  • GCDs of given index ranges in an Array
    Given an array arr[] of size N and Q queries of type {qs, qe} where qs and qe denote the starting and ending index of the query, the task is to find the GCD of all the numbers in the range. Examples: Input: arr[] = {2, 3, 60, 90, 50};Index Ranges: {1, 3}, {2, 4}, {0, 2}Output: GCDs of given ranges a
    14 min read
  • Mean of range in array
    Given an array arr[] of n integers and q queries represented by an array queries[][], where queries[i][0] = l and queries[i][1] = r. For each query, the task is to calculate the mean of elements in the range l to r and return its floor value. Examples: Input: arr[] = [3, 7, 2, 8, 5] queries[][] = [[
    12 min read
  • Difference Array | Range update query in O(1)
    You are given an integer array arr[] and a list of queries. Each query is represented as a list of integers where: [1, l, r, x]: Adds x to all elements from arr[l] to arr[r] (inclusive).[2]: Prints the current state of the array.You need to perform the queries in order. Examples : Input: arr[] = [10
    11 min read
  • Range sum query using Sparse Table
    We have an array arr[]. We need to find the sum of all the elements in the range L and R where 0 <= L <= R <= n-1. Consider a situation when there are many range queries. Examples: Input : 3 7 2 5 8 9 query(0, 5) query(3, 5) query(2, 4) Output : 34 22 15Note : array is 0 based indexed and q
    8 min read
geeksforgeeks-footer-logo
Corporate & Communications Address:
A-143, 7th Floor, Sovereign Corporate Tower, Sector- 136, Noida, Uttar Pradesh (201305)
Registered Address:
K 061, Tower K, Gulshan Vivante Apartment, Sector 137, Noida, Gautam Buddh Nagar, Uttar Pradesh, 201305
GFG App on Play Store GFG App on App Store
Advertise with us
  • Company
  • About Us
  • Legal
  • Privacy Policy
  • In Media
  • Contact Us
  • Advertise with us
  • GFG Corporate Solution
  • Placement Training Program
  • Languages
  • Python
  • Java
  • C++
  • PHP
  • GoLang
  • SQL
  • R Language
  • Android Tutorial
  • Tutorials Archive
  • DSA
  • Data Structures
  • Algorithms
  • DSA for Beginners
  • Basic DSA Problems
  • DSA Roadmap
  • Top 100 DSA Interview Problems
  • DSA Roadmap by Sandeep Jain
  • All Cheat Sheets
  • Data Science & ML
  • Data Science With Python
  • Data Science For Beginner
  • Machine Learning
  • ML Maths
  • Data Visualisation
  • Pandas
  • NumPy
  • NLP
  • Deep Learning
  • Web Technologies
  • HTML
  • CSS
  • JavaScript
  • TypeScript
  • ReactJS
  • NextJS
  • Bootstrap
  • Web Design
  • Python Tutorial
  • Python Programming Examples
  • Python Projects
  • Python Tkinter
  • Python Web Scraping
  • OpenCV Tutorial
  • Python Interview Question
  • Django
  • Computer Science
  • Operating Systems
  • Computer Network
  • Database Management System
  • Software Engineering
  • Digital Logic Design
  • Engineering Maths
  • Software Development
  • Software Testing
  • DevOps
  • Git
  • Linux
  • AWS
  • Docker
  • Kubernetes
  • Azure
  • GCP
  • DevOps Roadmap
  • System Design
  • High Level Design
  • Low Level Design
  • UML Diagrams
  • Interview Guide
  • Design Patterns
  • OOAD
  • System Design Bootcamp
  • Interview Questions
  • Inteview Preparation
  • Competitive Programming
  • Top DS or Algo for CP
  • Company-Wise Recruitment Process
  • Company-Wise Preparation
  • Aptitude Preparation
  • Puzzles
  • School Subjects
  • Mathematics
  • Physics
  • Chemistry
  • Biology
  • Social Science
  • English Grammar
  • Commerce
  • World GK
  • GeeksforGeeks Videos
  • DSA
  • Python
  • Java
  • C++
  • Web Development
  • Data Science
  • CS Subjects
@GeeksforGeeks, Sanchhaya Education Private Limited, All rights reserved
We use cookies to ensure you have the best browsing experience on our website. By using our site, you acknowledge that you have read and understood our Cookie Policy & Privacy Policy
Lightbox
Improvement
Suggest Changes
Help us improve. Share your suggestions to enhance the article. Contribute your expertise and make a difference in the GeeksforGeeks portal.
geeksforgeeks-suggest-icon
Create Improvement
Enhance the article with your expertise. Contribute to the GeeksforGeeks community and help create better learning resources for all.
geeksforgeeks-improvement-icon
Suggest Changes
min 4 words, max Words Limit:1000

Thank You!

Your suggestions are valuable to us.

What kind of Experience do you want to share?

Interview Experiences
Admission Experiences
Career Journeys
Work Experiences
Campus Experiences
Competitive Exam Experiences