Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
Program to define data structure that supports range sum in Python
Suppose we want to develop a data structure that can build up with a list of integers, and there is a function to find sum of elements from index i to index j-1 whenever we require in an efficient way. There are two functions:
- Constructor that constructs a new instance with the integer array.
- get_sum(i, j) returns the sum of integers of array elements from starting index i and ending index j-1.
So, if the input is like array = [5,2,3,6,4,7,8,9,3,2] then construct an object obj, and call functions obj.get_sum(1,5) and obj.get_sum(4,8), then the output will be 15 and 28 respectively. As the first range elements are [2,3,6,4] so sum is 15 and second range elements are [4,7,8,9] here the sum is 28.
Approach Using Prefix Sum
To solve this efficiently, we use a prefix sum technique that precomputes cumulative sums. This allows O(1) range sum queries after O(n) preprocessing.
The algorithm follows these steps:
- Define constructor. This will take array
- sums := this is a list, initially insert 0
- for each x in array, do
- insert (x + (last item of sums)) at the end of sums
- Define a function get_sum() . This will take i, j
- return sums[j] - sums[i]
Implementation
Let us see the following implementation to get better understanding ?
class RangeSum:
def __init__(self, array):
self.sums = [0]
for x in array:
self.sums.append(x + self.sums[-1])
def get_sum(self, i, j):
return self.sums[j] - self.sums[i]
array = [5, 2, 3, 6, 4, 7, 8, 9, 3, 2]
obj = RangeSum(array)
print(obj.get_sum(1, 5))
print(obj.get_sum(4, 8))
15 28
How It Works
The prefix sum array stores cumulative sums where sums[i] contains the sum of all elements from index 0 to i-1 in the original array ?
array = [5, 2, 3, 6, 4, 7, 8, 9, 3, 2]
obj = RangeSum(array)
# Show the prefix sum array
print("Original array:", array)
print("Prefix sums: ", obj.sums)
print()
# Demonstrate range sum calculation
print("Range [1,5): elements", array[1:5], "sum =", obj.get_sum(1, 5))
print("Range [4,8): elements", array[4:8], "sum =", obj.get_sum(4, 8))
Original array: [5, 2, 3, 6, 4, 7, 8, 9, 3, 2] Prefix sums: [0, 5, 7, 10, 16, 20, 27, 35, 44, 47, 49] Range [1,5): elements [2, 3, 6, 4] sum = 15 Range [4,8): elements [4, 7, 8, 9] sum = 28
Time Complexity
| Operation | Time Complexity | Space Complexity |
|---|---|---|
| Constructor | O(n) | O(n) |
| get_sum(i, j) | O(1) | O(1) |
Conclusion
The prefix sum approach provides an efficient solution for range sum queries with O(1) query time after O(n) preprocessing. This data structure is ideal when you need to perform multiple range sum operations on the same array.
