Difference Arrays: O(1) Range Updates for Interview Problems

Some interview problems hand you a list of operations like "add 5 to every element from index 2 to 7" and then ask for the final array. Applying each update directly costs O(n) per operation. A difference array makes each update O(1).

The idea

Store d[i] = a[i] - a[i-1]. Adding v to the range [l, r] only changes two entries: d[l] += v and d[r+1] -= v. After all updates, one prefix sum over d rebuilds the array.

def apply_ranges(n, ops):
    d = [0] * (n + 1)
    for l, r, v in ops:
        d[l] += v
        d[r + 1] -= v
    out, run = [], 0
    for i in range(n):
        run += d[i]
        out.append(run)
    return out

Total cost: O(n + q) instead of O(n * q).

Problems where it is the intended answer

Extensions worth mentioning

Interview tip

Say the pattern out loud: "updates are offline and only the final state matters, so I'll record boundaries and sweep once." Then mention the off-by-one at r+1, which is the bug interviewers watch for.


Disclosure: I help build Linkjob AI coding interview assistant. These notes are independent practice material.