Skip to content
ΣDSA Patterns
Menu
Language

Difference Array

Guide 1 of 6 · Path 1 of 6

PreviousNext

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

Tested only
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

Difference array batch range updates.

Reflection