Program to update elements in a given range in Python


Suppose we have a list of numbers called nums and a list of operations. Here each operation has three fields [L, R, X], this indicated that we should increment by X all the elements from indices L to R (inclusive). We have to apply all operations and return the final list.

So, if the input is like nums = [8, 4, 2, -9, 4] operations = [ [0, 0, 3], [1, 3, 2], [2, 3, 5] ], then the output will be [11, 6, 9, -2, 4], as the initial list was [8, 4, 2, -9, 4].

  • Performing first operation [0, 0, 3] the list will be [11, 4, 2, -9, 4].
  • Performing first operation [1, 3, 2] the list will be [11, 6, 4, -7, 4].
  • Performing first operation [2, 3, 5] the list will be [11, 6, 9, -2, 4].

To solve this, we will follow these steps −

  • events := a new list
  • for each (l, r, inc) in operations, do
    • insert (l, inc) at the end of events
    • insert (r + 1, -inc) at the end of events
  • sort the list events
  • inc := 0, ptr := 0
  • for i in range 0 to size of nums, do
    • while ptr < size of events and events[ptr, 0] is same as i, do
      • inc := inc + events[ptr, 1]
      • ptr := ptr + 1
    • nums[i] := nums[i] + inc
  • return nums

Let us see the following implementation to get better understanding −

Example

 Live Demo

class Solution:
   def solve(self, nums, operations):
      events = []
      for l, r, inc in operations:
         events.append((l, inc))
         events.append((r + 1, -inc))
      events.sort()
      inc = 0
      ptr = 0
      for i in range(len(nums)):
         while ptr < len(events) and events[ptr][0] == i:
            inc += events[ptr][1]
            ptr += 1
         nums[i] += inc
      return nums
ob = Solution()
nums = [8, 4, 2, -9, 4]
operations = [ [0, 0, 3], [1, 3, 2], [2, 3, 5] ]
print(ob.solve(nums, operations))

Input

[1,2,3,4,5,6,7,8,9,10], 3

Output

[11, 6, 9, -2, 4]

Updated on: 20-Oct-2020

223 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements