Range Updates via Difference Array: $O(1)$ Update Time
Applying $Q$ range additions of the form $\text{add}(L, R, V)$ directly across an array of size $N$ takes $O(Q \cdot N)$ time, which becomes prohibitively slow when $Q$ and $N$ reach $10^5$.
A Difference Array reduces every range addition query to just two $O(1)$ boundary updates. After all queries are processed, a single $O(N)$ prefix sum pass restores the updated values, slashing the total workload to $O(N + Q)$.
The Mathematical Foundation
Let $A$ be an array of length $N$. Its difference array $D$ is defined by the differences between adjacent elements:
$$D[0] = A[0]$$ $$D[i] = A[i] - A[i - 1] \quad \text{for } 1 \le i < N$$
Because prefix summation is the exact inverse operation of taking differences, computing the running cumulative sum of $D$ reconstructs the original array:
$$A[i] = \sum_{k=0}^{i} D[k]$$
Why the $O(1)$ Range Update Works
Suppose we want to add a value $V$ to all indices in the closed interval $[L, R]$:
- For indices inside the range ($L < i \le R$), both $A[i]$ and $A[i-1]$ increase by $V$, so their relative difference remains completely unchanged: $$(A[i] + V) - (A[i - 1] + V) = A[i] - A[i - 1] = D[i]$$
- Only the boundaries change:
- At index $L$, $A[L]$ increases by $V$ while $A[L - 1]$ does not. Thus, $D[L]$ increases by $V$.
- At index $R + 1$, $A[R + 1]$ remains unchanged while $A[R]$ was increased by $V$. Thus, $D[R + 1]$ decreases by $V$.
Therefore, updating the entire range $[L, R]$ requires modifying only two positions in $D$: $$D[L] \mathrel{+}= V$$ $$D[R + 1] \mathrel{-}= V \quad (\text{provided } R + 1 < N)$$
When calculating the prefix sum later, the addition of $+V$ at index $L$ naturally propagates forward across all indices $\ge L$. The compensating subtraction of $-V$ at index $R + 1$ halts the propagation, leaving indices beyond $R$ unaffected.
Trace Walkthrough: $N = 5$, Initial Array = [0, 0, 0, 0, 0]
- Initial State:
- $D = [0, 0, 0, 0, 0]$
- Update 1: Add $+3$ on range $[1, 3]$:
- $D[1] \mathrel{+}= 3$
- $D[3 + 1] \mathrel{-}= 3 \implies D[4] \mathrel{-}= 3$
- $D = [0, \mathbf{3}, 0, 0, \mathbf{-3}]$
- Update 2: Add $+5$ on range $[2, 4]$:
- $D[2] \mathrel{+}= 5$
- $R + 1 = 5 \ge N$ (out of bounds, ignore)
- $D = [0, 3, \mathbf{5}, 0, -3]$
- Reconstruct Final Array via Prefix Sum:
- $A[0] = D[0] = 0$
- $A[1] = A[0] + D[1] = 0 + 3 = 3$
- $A[2] = A[1] + D[2] = 3 + 5 = 8$
- $A[3] = A[2] + D[3] = 8 + 0 = 8$
- $A[4] = A[3] + D[4] = 8 + (-3) = 5$
- Result:
[0, 3, 8, 8, 5]
Implementation (C++ and Python)
C++ Implementation
#include <vector>
class DifferenceArray {
private:
std::vector<long long> diff;
int n;
public:
// Initialize with a given base array
DifferenceArray(const std::vector<int>& arr) {
n = arr.size();
diff.assign(n + 1, 0); // n + 1 size avoids boundary checks on (R + 1)
diff[0] = arr[0];
for (int i = 1; i < n; ++i) {
diff[i] = arr[i] - arr[i - 1];
}
}
// Apply range addition: O(1) time
void update(int l, int r, long long val) {
diff[l] += val;
diff[r + 1] -= val;
}
// Reconstruct final array: O(N) time
std::vector<long long> getResult() {
std::vector<long long> result(n);
result[0] = diff[0];
for (int i = 1; i < n; ++i) {
result[i] = result[i - 1] + diff[i];
}
return result;
}
};
Python Implementation
class DifferenceArray:
def __init__(self, arr: list[int]):
self.n = len(arr)
# Allocate n + 1 slots to cleanly handle r + 1 == n
self.diff = [0] * (self.n + 1)
self.diff[0] = arr[0]
for i in range(1, self.n):
self.diff[i] = arr[i] - arr[i - 1]
def update(self, l: int, r: int, val: int) -> None:
"""Applies range update [l, r] in O(1) time."""
self.diff[l] += val
self.diff[r + 1] -= val
def get_result(self) -> list[int]:
"""Reconstructs the array via prefix sum in O(N) time."""
result = [0] * self.n
result[0] = self.diff[0]
for i in range(1, self.n):
result[i] = result[i - 1] + self.diff[i]
return result
Complexity & Operational Trade-offs
| Metric | Naive Iterative Update | Difference Array |
|---|---|---|
| Single Update Time | $O(N)$ | $O(1)$ |
| Total Update Time ($Q$ queries) | $O(Q \cdot N)$ | $O(Q)$ |
| Reconstruction / Query Time | Free ($O(1)$ per cell) | $O(N)$ one-time prefix pass |
| Overall Complexity | $O(Q \cdot N)$ | $O(N + Q)$ |
| Auxiliary Space | $O(1)$ | $O(N)$ |
- Offline Limitation: The difference array technique requires all updates to be known in advance (or batched together) before querying individual values. If updates and queries are interleaved online, a dynamic tree structure like a Binary Indexed Tree (Fenwick Tree) or Segment Tree with Lazy Propagation ($O(\log N)$ update and query) should be used instead.
