Sum of Query II | Practice | GeeksforGeeks

You are given an array arr[] of n integers and q queries in an array queries[] of length 2*q containing l, r pair for all q queries. You need to compute the following sum over q queries.
 
Array is 1-Indexed.
Example 1:
Input: n = 4
arr = {1, 2, 3, 4}
q = 2
queries = {1, 4, 2, 3}
Output: 10 5
Explaination: In the first query we need sum 
from 1 to 4 which is 1+2+3+4 = 10. In the 
second query we need sum from 2 to 3 which is 
2 + 3 = 5.
Your Task:
You do not need to read input or print anything. Your task is to complete the function querySum() which takes n, arr, q and queries as input parameters and returns the answer for all the queries.
Expected Time Complexity: O(n+q)
Expected Auxiliary Space: O(n)
Constraints:
1 ≤ n, q ≤ 1000
1 ≤ arri ≤ 106
1 ≤ l ≤ r ≤ n
0
18pa1a04771 month ago
0.2/1.9 sec using square root decompositio
import math
class Solution:
    def querySum(self, n, arr, q, qe):
        val=int(math.sqrt(n))
        d={}
        for i in range(n):
            if (i+1)//val in d:
                d[(i+1)//val]=d[(i+1)//val]+arr[i]
            else:
                d[(i+1)//val]=arr[i]
        ans=[]
        for l in range(0,len(qe),2):
            s=0
            lf=qe[l]
            ri=qe[l+1]
            for k in range(lf,ri+1):
                if k//val==lf//val+1:
                    break
                s=s+arr[k-1]
            if lf//val==ri//val:
                ans.append(s)
                continue
            for k in range(ri,lf-1,-1):
                if k//val==ri//val-1:
                    break
                s=s+arr[k-1]
            for k in range((lf//val)+1,(ri//val)):
                if k in d:
                    s=s+d[k]
            ans.append(s)
        return ans
0
kiransaisk4481 month ago
simple python solution:
class Solution:
    def querySum(self, n, arr, q, queries):
        # code here
        result = []
        for i in range(0, 2*q-1, 2):
            left = queries[i] - 1
            right = queries[i+1]
            result.append(sum(arr[left:right]))
        return result
0
mohankumarit20012 months ago
 vector<int> querySum(int n, int arr[], int q, int queries[])
    {
        for(int i=1;i<n;i++){
            arr[i]+=arr[i-1];
        }
        vector<int> res;
        for(int i=0;i<2*q;i+=2){
            if(queries[i]==0)res.push_back(arr[queries[i+1]-1]);
            res.push_back(arr[queries[i+1]-1]-arr[queries[i]-2]);
        }
        return res;
    }
0
annanyamathur2 months ago
Using Segment Tree
 
int tree[100000];int getSum(int l,int r,int start,int end,int index){   if(l>end || r<start)   return 0;   if(start>=l && end<=r)   return tree[index];   int mid=(start+end)/2;   return getSum(l,r,start,mid,2*index+1)+getSum(l,r,mid+1,end,2*index+2);}void constructST(int arr[],int start,int end,int index){   if(start==end)   {tree[index]=arr[start];   return;   }   int mid=(start+end)/2;   constructST(arr,start,mid,2*index+1);   constructST(arr,mid+1,end,2*index+2);   tree[index]=tree[2*index+1]+tree[2*index+2];   }   vector<int> querySum(int n, int arr[], int q, int queries[])   {        vector<int>r;        constructST(arr,0,n-1,0);                for(int i=0;i<2*q;i+=2)        {  //cout<<i<<"\t"<<queries[i]<<"\t"<<queries[i+1]<<"\n";            int a=getSum(queries[i]-1,queries[i+1]-1,0,n-1,0);            r.push_back(a);        }        return r;   }
0
kantariyaraj3 months ago
Simple Java solution
if(n == 0 || q == 0) return null;
       List<Integer> result = new ArrayList<>();
       int[] sumList = new int[n];
       sumList[0] = arr[0];
       for(int i = 1; i < n; i++){
           sumList[i] = arr[i] + sumList[i-1]; 
       }
       
       for(int i = 0; i < q; i++){
           int l = queries[2 * i] - 1;
           int r= queries[(2 * i) + 1] - 1;
           result.add(sumList[r]-sumList[l]);
       }
       
       return result;

0
chessnoobdj5 months ago
Optimized c++ using prefix sum
vector<int> querySum(int n, int arr[], int q, int queries[])
    {
        vector <int> ans;
        for(int i=1; i<n; i++)
            arr[i] += arr[i-1];
        for(int i=0; i<2*q; i += 2){
            if(queries[i] == 1)
                ans.push_back(arr[queries[i+1]-1]);
            else
                ans.push_back(arr[queries[i+1]-1] - arr[queries[i]-2]);
        }
        return ans;
    }
0
gurshaansing6 months ago
vector<int> ans;       int i=0;       while(q--)       {           int count=0;           int start=queries[i];           int end=queries[i+1];           for(int j=start-1;j<end && j<n;j++)           {               count+=arr[j];           }           ans.push_back(count);           i+=2;       }       return ans;
0
Suraj Kumar Modi7 months ago
Suraj Kumar Modi
Simple JAVA SolutionExecution time : 0.04 sec
class Solution{    List<integer> querySum(int n, int arr[], int q, int queries[])    {        List<integer> ob = new ArrayList<integer>();        int l = q * 2;        for(int i=0;i<l-1;i=i+2) {="" ob.add(sum(arr,queries[i],queries[i+1]));="" }="" return="" ob;="" }="" public="" int="" sum(int="" arr[],int="" l,int="" r)="" {="" int="" sum="0;" l="l" -="" 1;="" r="r" -="" 1;="" for(int="" i="l;i&lt;=r;i++)" sum+="arr[i];" return="" sum;="" }="" }="" <="" code="">
0
19wh1a05367 months ago
Python3
Total Time Taken : 0.3 / 1.9
 
class Solution:   def querySum(self, n, arr, q, queries):       # code here       sol = []       for i in range(0, len(queries), 2):           j = i+1           ans = 0           for a in range(queries[i]-1,queries[j]):               ans += arr[a]           sol.append(ans)       return sol 
0
pushpakninave0077 months ago
they havent mentioned that the array is sorted. either way it would be easy pheeeew.....
We strongly recommend solving this problem on your own before viewing its editorial. Do you still
                    want to view the editorial?
 Login to access your submissions. 

Problem


Contest

Reset the IDE using the second button on the top right corner.
Avoid using static/global variables in your code as your code is tested against multiple test cases and these tend to retain their previous values.
Passing the Sample/Custom Test cases does not guarantee the correctness of code. On submission, your code is tested against multiple test cases consisting of all possible corner cases and stress constraints.
You can access the hints to get an idea about what is expected of you as well as the final solution code.
You can view the solutions submitted by other users from the submission tab.