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.

To solve this, we will follow 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]

Example

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))

Input

[5,2,3,6,4,7,8,9,3,2]
obj.get_sum(1,5)
obj.get_sum(4,8)

Output

15
28

Updated on: 14-Oct-2021

123 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements