Program to update elements in a given range in Python

Suppose we have a list of numbers called nums and a list of operations. Each operation has three fields [L, R, X], which indicates 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] and operations = [[0, 0, 3], [1, 3, 2], [2, 3, 5]], then the output will be [11, 6, 9, -2, 4].

Step-by-Step Process

Let's trace through the operations with the initial list [8, 4, 2, -9, 4] ?

  • Performing operation [0, 0, 3]: Add 3 to index 0 ? [11, 4, 2, -9, 4]
  • Performing operation [1, 3, 2]: Add 2 to indices 1-3 ? [11, 6, 4, -7, 4]
  • Performing operation [2, 3, 5]: Add 5 to indices 2-3 ? [11, 6, 9, -2, 4]

Algorithm

To solve this efficiently, we'll use a difference array approach ?

  • Create an events list to store start and end points of operations
  • For each operation [l, r, inc], add (l, inc) and (r + 1, -inc) to events
  • Sort the events by index
  • Process events and apply cumulative increments to the original array

Example

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

# Test the solution
ob = Solution()
nums = [8, 4, 2, -9, 4]
operations = [[0, 0, 3], [1, 3, 2], [2, 3, 5]]
result = ob.solve(nums, operations)
print("Final result:", result)
Final result: [11, 6, 9, -2, 4]

How It Works

The algorithm uses a sweep line technique ?

  1. Events creation: For operation [l, r, x], we mark index l as "start adding x" and index r+1 as "stop adding x"
  2. Sorting: Events are sorted by index to process them in order
  3. Sweeping: We iterate through each index, updating the cumulative increment and applying it to the current element

Alternative Approach

Here's a simpler but less efficient approach using direct range updates ?

def update_range_simple(nums, operations):
    # Create a copy to avoid modifying the original
    result = nums[:]
    
    for l, r, x in operations:
        for i in range(l, r + 1):
            result[i] += x
    
    return result

# Test the simple approach
nums = [8, 4, 2, -9, 4]
operations = [[0, 0, 3], [1, 3, 2], [2, 3, 5]]
result = update_range_simple(nums, operations)
print("Simple approach result:", result)
Simple approach result: [11, 6, 9, -2, 4]

Comparison

Approach Time Complexity Space Complexity Best For
Difference Array O(n + m log m) O(m) Many operations
Direct Update O(n × m) O(1) Few operations

Where n is the length of nums and m is the number of operations.

Conclusion

The difference array approach efficiently handles multiple range updates by converting them to point updates. This technique is particularly useful when dealing with many overlapping range operations on large arrays.

Updated on: 2026-03-25T11:33:22+05:30

402 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements