- Trending Categories
Data Structure
Networking
RDBMS
Operating System
Java
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
Physics
Chemistry
Biology
Mathematics
English
Economics
Psychology
Social Studies
Fashion Studies
Legal Studies
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
Range Sum Query - Immutables in C++
Suppose we have an array of integers. We have to find the sum of the elements present from index i to j. Two things we have to keep in mind that the array will be immutable, so elements will not be altered, and there will be multiple such queries. So we have to care about the execution time for a large number of queries. Suppose the array is like A = [5, 8, 3, 6, 1, 2, 5], then if query is (A, 0, 3), then it will be 5 + 8 + 3 + 6 = 22.
To solve this, we will follow these steps −
- Take one array B. B[i] will store the sum of elements from 0 to i
- for query perform B[j] – B[i – 1]
Let us see the following implementation to get a better understanding −
Example
#include <bits/stdc++.h> using namespace std; class NumArray { public: vector <int> pre; NumArray(vector<int>& nums) { pre.clear(); int n = nums.size(); pre.resize(n); for(int i = 0; i < n; i++){ if(i == 0)pre[0] = nums[0]; else pre[i] = pre[i - 1] + nums[i]; } } int sumRange(int i, int j) { if(i == 0)return pre[j]; return pre[j] - pre[i - 1]; } }; main(){ vector<int> v = {5,8,3,6,1,2,5}; NumArray na(v); cout<<na.sumRange(0,2)<<endl; cout<<na.sumRange(2,5)<<endl; cout<<na.sumRange(0,5)<<endl; }
Input
Initialize it with [5,8,3,6,1,2,5] Call sumRange(0,2) sumRange(2,5) sumRange(0,5)
Output
16 12 25
- Related Articles
- Range Sum Query 2D - Immutable in C++
- Range Sum Query 2D - Mutable in C++
- C++ Range Sum Query Using Sparse Table
- Find the Number of Prefix Sum Prime in Given Range Query using C++
- Count of Range Sum in C++
- Construct sum-array with sum of elements in given range in C++
- Maximum Subarray Sum in a given Range in C++
- Range Sum Queries Without Updates using C++
- Maximum prefix-sum for a given range in C++
- C++ Program for Range sum queries without updates?
- C++ Program for the Range sum queries without updates?
- C++ Range Sum Queries and Update with Square Root
- C++ code to check query for 0 sum
- Find the Number Of Subarrays Having Sum in a Given Range in C++
- Ignoring the year in MySQL Query with date range?

Advertisements