Skip to content
DSA Patterns
Menu
Language
Difference ArrayLC #3701 of 6Next →

Demo preview: These solutions pass the automated test suite but have not been human-reviewed. Treat trade-offs and prose as draft.

Range Addition

Problem (restated)

Array of length length starts at 0. updates[i] = [start, end, inc] adds inc to inclusive range. Return final array.

Intuition

+inc at start, -inc at end+1; prefix sum materializes the array in O(n).

Approaches

Difference array range updates

Unverified
Time O(n + u)Space O(n)

Idea. Classic difference array. Avoid O(n) per update.

Walkthrough. length=5, [[1,3,2],[2,4,3],[0,2,-2]] → [-2,0,3,5,3].

Trade-offs. Segment tree only needed for online queries mixed with updates.

Solution
export function getModifiedArray(length: number, updates: number[][]): number[] {
  const diff = Array(length + 1).fill(0);
  for (const u of updates) {
    diff[u[0]!] += u[2]!;
    diff[u[1]! + 1] -= u[2]!;
  }
  const res = Array(length).fill(0);
  let cur = 0;
  for (let i = 0; i < length; i++) {
    cur += diff[i]!;
    res[i] = cur;
  }
  return res;
}
export function getModifiedArray(length: number, updates: number[][]): number[] {
  const diff = Array(length + 1).fill(0);
  for (const u of updates) {
    diff[u[0]!] += u[2]!;
    diff[u[1]! + 1] -= u[2]!;
  }
  const res = Array(length).fill(0);
  let cur = 0;
  for (let i = 0; i < length; i++) {
    cur += diff[i]!;
    res[i] = cur;
  }
  return res;
}

Template connection

Range-add shape: diff[L] += v and diff[R+1] -= v, then one prefix rebuild. Each update stays O(1) because the range itself is never walked.

Reflection

  • Writing each update straight into the array costs updates * n. You do diff[l] += v and diff[r + 1] -= v, then one prefix. Why is that enough?
  • When r + 1 == n, where does the subtraction go? If the array is only length n, does the last cell disappear?
  • Overlapping updates add up in the prefix. With no updates, is the answer n zeros?
Contributor review checklist

Interactive

Mental model

A worked animation for this problem. Scrub steps or press space to pause; re-tell the invariant out loud.

Step 1 of 6
1/6

Range addition on a length-5 zero array. Write +inc at L, −inc at R+1.

0
0
0
1
0
2
0
3
0
4

updates = 3

Key:CurrentActive rangeMatchSettledEliminated