Talentd
FleetCode

370. Range Addition

Medium73.0% acceptance2 companiesPremium elsewhere, free here

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. In the ith operation, you should increment all the elements arr[startIdxi], arr[startIdxi + 1], ..., arr[endIdxi] by inci.

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 <= 105
  • 0 <= updates.length <= 104
  • 0 <= startIdxi <= endIdxi < length
  • -1000 <= inci <= 1000

Asked at 2 companies

Hints open one at a time

Hint 1
Thinking of using advanced data structures? You are thinking it too complicated.
Hint 2
For each update operation, do you really need to update all elements between i and j?
Hint 3
Update only the first and end element is sufficient.
Hint 4
The optimal time complexity is O(k + n) and uses O(1) extra space.
24:34
Still stuck?Read 2 approaches, or watch a walkthrough.
Open solution
Loading editor…
1class Solution:
2 def solve(self):
3 pass
4
Starter codePython 3Spaces: 4
Examples
Input
5
[[1,3,2],[2,4,3],[0,2,-2]]
Input
10
[[2,4,6],[5,6,8],[1,9,-4]]
Your code is saved on this device.Solution