Python Program for Range sum queries without updates
Last Updated :
29 Nov, 2022
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
Method 1:
Python3
def find_ans(ar, j, k):
l = len (ar)
for i in range ( 1 , l):
ar[i] = ar[i] + ar[i - 1 ]
print (ar[k] - ar[j - 1 ])
return ;
pr = [ 1 , 2 , 3 , 4 , 5 ]
ar = pr[:]
find_ans(ar, 1 , 3 )
ar = pr[:]
find_ans(ar, 2 , 4 )
|
Time Complexity: O(n), where n represents the size of the given array.
Auxiliary Space: O(n), where n represents the size of the given array.
Please refer complete article on Range sum queries without updates for more details!
Method 2:
List splicing may be used, along with sum function, for a one-line approach to this problem.
Python3
def find_ans(ar, j, k):
print ( sum (ar[j:k + 1 ]))
ar = [ 1 , 2 , 3 , 4 , 5 ]
find_ans(ar, 1 , 3 )
find_ans(ar, 2 , 4 )
|
Time Complexity: O(n), where n represents the size of the given array.
Auxiliary Space: O(1)
Like Article
Suggest improvement
Share your thoughts in the comments
Please Login to comment...