Range Addition - 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 operations to apply on arr.

In the i-th operation, you should increment all the elements arr[startIdxi], arr[startIdxi + 1], ..., arr[endIdxi] by inci.

Return arr after applying all the updates.

Input & Output

Example 1 — Basic Range Updates
$ Input: length = 5, updates = [[1,3,2],[2,4,3],[0,2,-2]]
Output: [-2,0,3,5,3]
💡 Note: Start with [0,0,0,0,0]. After [1,3,2]: [0,2,2,2,0]. After [2,4,3]: [0,2,5,5,3]. After [0,2,-2]: [-2,0,3,5,3].
Example 2 — Single Update
$ Input: length = 10, updates = [[2,4,6]]
Output: [0,0,6,6,6,0,0,0,0,0]
💡 Note: Add 6 to indices 2,3,4. All other positions remain 0.
Example 3 — Overlapping Updates
$ Input: length = 3, updates = [[0,1,1],[1,2,1]]
Output: [1,2,1]
💡 Note: First update: [1,1,0]. Second update adds to indices 1,2: [1,2,1].

Constraints

  • 1 ≤ length ≤ 105
  • 0 ≤ updates.length ≤ 104
  • 0 ≤ startIdxi ≤ endIdxi < length
  • -1000 ≤ inci ≤ 1000

Visualization

Tap to expand
Range Addition - Optimal Solution INPUT Initial Array (length=5) 0 0 0 0 0 0 1 2 3 4 Updates Array: [1, 3, 2] add 2 to idx 1-3 [2, 4, 3] add 3 to idx 2-4 [0, 2, -2] add -2 to idx 0-2 Naive: O(n*k) per update Optimal: O(n+k) total ALGORITHM STEPS 1 Mark Boundaries arr[start] += inc arr[end+1] -= inc 2 Apply Update 1 [1,3,2]: arr[1]+=2, arr[4]-=2 3 Apply Update 2 [2,4,3]: arr[2]+=3, arr[5]-=3 4 Apply Update 3 [0,2,-2]: arr[0]+=-2, arr[3]-=-2 Difference Array: -2 2 1 2 0 5 Prefix Sum Accumulate values left to right for final array FINAL RESULT Prefix Sum Calculation: i=0: sum = -2 i=1: sum = -2+2 = 0 i=2: sum = 0+1 = 1 i=3: sum = 1+2 = 3 i=4: sum = 3+0 = 3 Output Array: -2 0 1 3 3 0 1 2 3 4 [-2,0,1,3,3] OK Key Insight: Instead of updating every element in range (O(k) per update), mark only the boundaries: add value at start index and subtract at end+1 index. This creates a "difference array". A single prefix sum pass at the end reconstructs the actual values in O(n) time. Time: O(n + k) | Space: O(1) extra (modifying input array) TutorialsPoint - Range Addition | Difference Array Approach
Asked in
Google 25 Amazon 20 Microsoft 15
32.0K Views
Medium Frequency
~25 min Avg. Time
850 Likes
Ln 1, Col 1
Smart Actions
💡 Explanation
AI Ready
💡 Suggestion Tab to accept Esc to dismiss
// Output will appear here after running code
Code Editor Closed
Click the red button to reopen