Range Addition — LeetCode 370 Python Solution
- Problem
- #370
- Pattern
- Prefix Sum
- Reading time
- 2 min
- Source
- leetcode.com
The problem
You are given an integer length and an array updates where updates[i] = [startIdxi, endIdxi, inci]. You have an array arr of length length with all zeros, and you have some operation to apply on arr.
Example
- Input
- length = 5, updates = [[1,3,2],[2,4,3],[0,2,-2]]
- Output
- [-2,0,3,5,3]
Python solution
class Solution:
def getModifiedArray(self, length: int, updates: List[List[int]]) -> List[int]:
d = [0] * length
for l, r, c in updates:
d[l] += c
if r + 1 < length:
d[r + 1] -= c
return list(accumulate(d))Complexity
| Measure | Complexity |
|---|---|
| Time | O(n) |
| Space | O(n) auxiliary |
Pattern: Prefix Sum
Precompute running totals once so any range query becomes a single subtraction. LeetCode 370. Range Addition is filed here on both counts: the reference solution below belongs to the algorithm family this hub collects, and LeetCode tags it Prefix Sum.
The prefix sum guide has the Python template for the pattern and the 157 LeetCode problems that use it.
Related problems
Frequently asked questions
- How hard is LeetCode 370. Range Addition?
- LeetCode 370. Range Addition is rated Medium on LeetCode.
- What is the time complexity of LeetCode 370. Range Addition?
- The Python solution on this page runs in O(n).
- What is the space complexity of LeetCode 370. Range Addition?
- The Python solution on this page uses O(n) auxiliary space.
- What topics does LeetCode 370. Range Addition cover?
- LeetCode 370. Range Addition is tagged Array and Prefix Sum on LeetCode.
- Is LeetCode 370. Range Addition a premium problem?
- Yes. LeetCode 370. Range Addition is a LeetCode Premium problem, so the full statement and test cases require a paid LeetCode subscription.