Range Addition Problem
Description
LeetCode Problem 370.
You are given an integer length and an array updates where updates[i] = [startIdx_i, endIdx_i, inc_i].
You have an array arr of length length with all zeros, and you have some operation to apply on arr. In the i^th operation, you should increment all the elements arr[startIdx_i], arr[startIdx_i + 1], ..., arr[endIdx_i] by inc_i.
Return arr after applying all the updates.
Example 1:

Input: length = 5, updates = [[1,3,2],[2,4,3],[0,2,-2]]
Output: [-2,0,3,5,3]
Example 2:
Input: length = 10, updates = [[2,4,6],[5,6,8],[1,9,-4]]
Output: [0,-4,2,2,2,4,4,-4,-4,-4]
Constraints:
1 <= length <= 10^50 <= updates.length <= 10^40 <= startIdx_i <= endIdx_i < length-1000 <= inc_i <= 1000
Solution
Approach: Difference Array
Applying each update to every element in its range takes O(length) per update, which is up to 109 steps in total. A difference array turns each range update into two single writes.
Let diff[i] = arr[i] - arr[i - 1] (with arr[-1] = 0). Adding inc to arr[start..end] changes only two of these differences: diff[start] goes up by inc, because arr[start] rose but its left neighbor did not, and diff[end + 1] goes down by inc, because arr[end + 1] did not rise but its left neighbor did. Every difference inside the range stays the same.
So, for each update, do diff[start] += inc and diff[end + 1] -= inc. Then rebuild the array with a running sum: arr[i] = diff[0] + diff[1] + ... + diff[i]. Make diff one longer than the array, so that end + 1 = length needs no special case. An empty list of updates simply leaves all zeros.
Complexity: O(length + u) time for u updates. O(length) space for the difference array.
class Solution:
def getModifiedArray(self, length: int, updates: List[List[int]]) -> List[int]:
# diff[i] = arr[i] - arr[i - 1]: adding inc to arr[start..end] only changes
# diff[start] (+inc) and diff[end + 1] (-inc)
diff = [0] * (length + 1)
for start, end, inc in updates:
diff[start] += inc
diff[end + 1] -= inc
arr, running = [0] * length, 0
for i in range(length):
running += diff[i]
arr[i] = running
return arr