Simple Algorithm
Algorithms & Data Structures · Optimal · 24 min

Difference Arrays & Sweep Lines

Range updates in O(1), interval overlaps and event sweeps.

For arrays, prefix sums are integrals and differences are derivatives, and the analogy is exact. It turns "add a ramp to each of a million ranges" into three point updates per ramp, and "how many meetings overlap?" into sorting 2n2n events. Pushed into the plane, the same sweep finds every crossing among nn segments, and it is still a research topic in higher dimensions.

What you’ll learn

  • Prove that the prefix-sum and difference operators are inverse linear maps, and use linearity to batch qq range updates offline in O(n+q)O(n+q).
  • Add a degree-dd polynomial to a range with at most 2(d+1)2(d+1) point updates on the (d+1)(d+1)-th difference, and add a constant to a rectangle with four corner updates.
  • Compute maximum overlaps by sweeping sorted events with the correct tie rule, and prove an Ω(nlog⁡n)\Omega(n\log n) lower bound in the algebraic decision tree model.
  • Explain the Bentley–Ottmann sweep, the optimal O(nlog⁡n+k)O(n\log n+k) bound for segment intersection, and Klee's measure problem as the frontier of sweeping.

Differences are derivatives

The difference array of the Optimized lesson is an operator. On sequences of length nn, define the inclusive prefix sum Σ\Sigma and the backward difference Δ\Delta:

(Σa)[i]=∑j=0ia[j],(Δa)[i]=a[i]−a[i−1]with a[−1]=0.(\Sigma a)[i]=\sum_{j=0}^{i}a[j],\qquad(\Delta a)[i]=a[i]-a[i-1]\quad\text{with }a[-1]=0.

In the course's prefix notation, (Σa)[i]=P[i+1](\Sigma a)[i]=P[i+1].

DerivationProof, and what it buys
  1. (ΔΣa)[i]=∑j=0ia[j]−∑j=0i−1a[j]=a[i](\Delta\Sigma a)[i]=\sum_{j=0}^{i}a[j]-\sum_{j=0}^{i-1}a[j]=a[i]

    Differencing a prefix sum leaves its last term:

  2. (ΣΔa)[i]=∑j=0i(a[j]−a[j−1])=a[i]−a[−1]=a[i](\Sigma\Delta a)[i]=\sum_{j=0}^{i}\big(a[j]-a[j-1]\big)=a[i]-a[-1]=a[i]

    Summing differences telescopes, and a[−1]=0a[-1]=0:

  3. Σ=(1111111111),Δ=Σ−1=(1−11−11−11)\Sigma=\begin{pmatrix}1&&&\\1&1&&\\1&1&1&\\1&1&1&1\end{pmatrix},\qquad\Delta=\Sigma^{-1}=\begin{pmatrix}1&&&\\-1&1&&\\&-1&1&\\&&-1&1\end{pmatrix}

    As matrices, Σ\Sigma is the lower-triangular matrix of ones, and its inverse Δ\Delta has ones on the diagonal and −1-1 just below it:

  4. Δ(a+v 1[l,r])=Δa+v (el−er+1)\Delta\big(a+v\,\mathbf 1_{[l,r]}\big)=\Delta a+v\,(e_l-e_{r+1})

    A range update adds vv times the indicator of [l,r][l,r], whose difference is two spikes (drop er+1e_{r+1} when r=n−1r=n-1). By linearity, qq updates cost O(q)O(q) on Δa\Delta a, and one application of Σ\Sigma rebuilds aa in O(n)O(n): O(n+q)O(n+q) in total, against up to Θ(nq)\Theta(nq) for looping over each range.

Online, when reads arrive between updates, store Δa\Delta a in a Fenwick tree: a range update is two point updates, and reading a[i]=(ΣΔa)[i]a[i]=(\Sigma\Delta a)[i] is a prefix sum, each O(log⁡n)O(\log n). A second Fenwick tree supports range sums as well (see Fenwick Trees in Depth).

Higher-order differences: polynomials on ranges

Suppose each update adds a ramp 1,2,…,k1,2,\dots,k to a[l..r]a[l..r], where k=r−l+1k=r-l+1. Its first difference is +1+1 on all of [l,r][l,r], no longer sparse. But that is itself a range update plus one spike, so take the difference once more.

DerivationThe second difference of a ramp
  1. (Δf)[i]={1l≤i≤r−ki=r+10otherwise(\Delta f)[i]=\begin{cases}1 & l\le i\le r\\ -k & i=r+1\\ 0 & \text{otherwise}\end{cases}

    Let f(i)=i−l+1f(i)=i-l+1 on [l,r][l,r] and f(i)=0f(i)=0 elsewhere. Its first difference:

  2. (Δ2f)[i]={+1i=l−(k+1)i=r+1+ki=r+20otherwise(\Delta^2 f)[i]=\begin{cases}+1 & i=l\\ -(k+1) & i=r+1\\ +k & i=r+2\\ 0 & \text{otherwise}\end{cases}

    Difference again. Only the three places where Δf\Delta f changes value survive:

  3. a=Σ Σ (Δ2a)a=\Sigma\,\Sigma\,\big(\Delta^2 a\big)

    So each ramp costs three point updates on Δ2a\Delta^2 a, and two prefix passes rebuild the array:

python
from itertools import accumulate

def add_ramps(n, updates):
    D2 = [0] * (n + 2)                  # second differences, two spare slots
    for l, r in updates:                # add 1, 2, ..., k to a[l..r], k = r - l + 1
        k = r - l + 1
        D2[l] += 1
        D2[r + 1] -= k + 1
        D2[r + 2] += k
    d = list(accumulate(D2))            # first pass: the first differences
    return list(accumulate(d))[:n]      # second pass: the values

print(add_ramps(8, [(1, 4), (3, 6)]))   # [0, 1, 2, 4, 6, 3, 4, 0]
Check your understanding

Using third differences, at most how many point updates does adding a quadratic polynomial to one range require?

  1. 3
  2. 4
  3. 6
  4. 9
Show the answer

C. 6

With d=2d=2, the theorem allows up to d+1=3d+1=3 nonzero cells at the left end, [l,l+2][l,l+2], and 3 at the right end, [r+1,r+3][r+1,r+3]: at most 2(d+1)=62(d+1)=6. Three prefix passes then rebuild the array. (A particular quadratic can need fewer: 1,4,9,…1,4,9,\dots needs only 2 at the left end, because (t+1)2(t+1)^2 already vanishes at t=−1t=-1.)

In two dimensions, take differences along rows and then along columns. The difference of a rectangle's indicator is the product of two 1-D spike pairs, that is, four signed corners:

ΔrowΔcol 1[r1,r2]×[c1,c2]=(er1−er2+1)⊗(ec1−ec2+1)\Delta_{\text{row}}\Delta_{\text{col}}\,\mathbf 1_{[r_1,r_2]\times[c_1,c_2]}=\big(e_{r_1}-e_{r_2+1}\big)\otimes\big(e_{c_1}-e_{c_2+1}\big)
Add vv to a rectangle with +v+v at (r1,c1)(r_1,c_1) and (r2+1,c2+1)(r_2+1,c_2+1) and −v-v at (r1,c2+1)(r_1,c_2+1) and (r2+1,c1)(r_2+1,c_1); rebuild with prefix sums along each row, then along each column. Total O(RC+q)O(RC+q) for qq rectangles on an R×CR\times C grid.

Sweep lines: events instead of cells

With coordinates up to 10910^9, a difference array indexed by coordinate is out of the question, but only the 2n2n endpoints matter. Turn each half-open interval [s,e)[s,e) into two events, +1+1 at ss and −1-1 at ee, sort them, and sweep from left to right. The running sum is the number of intervals covering the current point: the prefix sum of the difference array, evaluated only where it can change. Its maximum is the maximum overlap, in O(nlog⁡n)O(n\log n) time for sorting plus O(n)O(n) for the sweep.

Equivalently, compress the endpoints to ranks 0..2n−10..2n-1 and use an ordinary difference array on the ranks.

python
def max_overlap(intervals):             # half-open [s, e)
    events = []
    for s, e in intervals:
        events.append((s, +1))
        events.append((e, -1))
    events.sort()                       # at equal x, -1 sorts first: ends before starts
    best = cur = 0
    for x, delta in events:
        cur += delta                    # cur = number of intervals covering x
        best = max(best, cur)
    return best

print(max_overlap([(9, 11), (11, 13), (10, 11), (11, 12)]))   # 2
Check your understanding

In the code above, suppose events at the same coordinate were processed starts first, then ends. What would it return for the half-open intervals [9,11),[11,13),[10,11),[11,12)[9,11),[11,13),[10,11),[11,12)?

  1. 2
  2. 3
  3. 4
  4. 1
Show the answer

C. 4

At x=11x=11 two meetings end and two begin. Starts first would count all four as running at once, 2+2=42+2=4, before the two endings are subtracted. Half-open intervals that touch at 11 never overlap, so the true answer is 2. Closed intervals [s,e][s,e] need the opposite rule: starts before ends.

The recipe generalizes: events sorted by coordinate, a status structure describing the sweep line, and an invariant about everything left of it. With a max-heap of active heights as the status, the sweep draws a skyline, the outline of nn overlapping rectangles standing on a line, in O(nlog⁡n)O(n\log n). With a segment tree over compressed yy-coordinates that supports range addition and a global maximum, it finds the point covered by the most of nn rectangles in O(nlog⁡n)O(n\log n) (see Lazy Propagation).

Sweeping the plane: Bentley–Ottmann and Klee

Shamos and Hoey (1976) decided whether any two of nn line segments intersect in O(nlog⁡n)O(n\log n) time. Sweep a vertical line from left to right and keep the segments it crosses in a balanced search tree, ordered by height. The key lemma: just before the leftmost crossing point, the two segments that cross there are adjacent in this order, so only neighbors ever need testing.

Bentley and Ottmann (1979) turned the test into a report of all kk crossing pairs. The event queue holds the endpoints plus the crossings of currently adjacent pairs. At a crossing the two segments swap places in the tree, and each is tested against its new neighbor.

Is that optimal? Not quite. When k=Θ(n2)k=\Theta(n^2), O(n2log⁡n)O(n^2\log n) is worse than testing all pairs. Chazelle and Edelsbrunner (1992) reached O(nlog⁡n+k)O(n\log n+k) time, and Balaban (1995) the same time in O(n)O(n) space, matching the Ω(nlog⁡n+k)\Omega(n\log n+k) lower bound in the algebraic decision tree model: Ω(nlog⁡n)\Omega(n\log n) just to decide whether any crossing exists, and kk to write the output.

Sweeps also measure unions. Klee's measure problem (Klee, 1977) asks for the total length of a union of nn intervals: sort and sweep in O(nlog⁡n)O(n\log n), which Fredman and Weide (1978) proved optimal in the linear decision tree model. The area of a union of nn rectangles takes O(nlog⁡n)O(n\log n) with a sweep and a segment tree that tracks the covered length of the sweep line (Bentley, 1977). In d≥3d\ge3 dimensions the best bound for boxes is O(nd/2)O(n^{d/2}), by Chan's (2013) strikingly simple divide and conquer, after Overmars and Yap's O(nd/2log⁡n)O(n^{d/2}\log n) (1991).

Key takeaways

  • Prefix summation Σ\Sigma and the backward difference Δ\Delta are inverse linear maps; a range update is two spikes in Δa\Delta a, so qq offline updates cost O(n+q)O(n+q).
  • A degree-dd polynomial added to a range touches at most 2(d+1)2(d+1) cells of Δd+1a\Delta^{d+1}a, and d+1d+1 prefix passes rebuild the array; a rectangle in 2-D is four signed corners.
  • A sweep line evaluates the difference array only at sorted events: maximum overlap in O(nlog⁡n)O(n\log n), optimal in the algebraic decision tree model; the tie rule depends on whether intervals are open or closed.
  • Bentley–Ottmann reports kk segment crossings in O((n+k)log⁡n)O((n+k)\log n); O(nlog⁡n+k)O(n\log n+k) is optimal; Klee's measure problem in d≥3d\ge3 dimensions sits at O(nd/2)O(n^{d/2}) with a polynomial gap to the known lower bounds.

Check yourself

In the interactive lesson these are scored with your confidence, and what you miss comes back for review.

Question 1

You add the ramp 1,2,…,k1,2,\dots,k to a[l..r]a[l..r], where k=r−l+1k=r-l+1, using an array of second differences. Which cells change?

  1. +1+1 at ll and −k-k at r+1r+1
  2. +1+1 at every cell of [l,r][l,r]
  3. +k+k at ll and −k-k at r+1r+1
  4. +1+1 at ll, −(k+1)-(k+1) at r+1r+1 and +k+k at r+2r+2
Show the answer

D. +1+1 at ll, −(k+1)-(k+1) at r+1r+1 and +k+k at r+2r+2

The first difference of the ramp is +1+1 on [l,r][l,r] and −k-k at r+1r+1. Its difference is +1+1 where it starts, −k−1-k-1 at r+1r+1 (from +1+1 down to −k-k), and +k+k at r+2r+2 (from −k-k back to 00).

Question 2

A sweep computes the maximum number of simultaneously running meetings. Meetings are closed intervals [s,e][s,e], so one ending at 11 and one starting at 11 do overlap at time 11. At equal coordinates, which events must come first?

  1. Ends before starts
  2. Starts before ends
  3. Either order gives the same maximum
  4. Longer meetings first
Show the answer

B. Starts before ends

For closed intervals the point 11 belongs to both meetings, so the starting meeting must be counted before the ending one is removed. For half-open intervals [s,e)[s,e) the rule flips.

Question 3

Why is Ω(nlog⁡n)\Omega(n\log n) a lower bound for the maximum overlap of nn intervals?

  1. Every algorithm must sort the endpoints
  2. In the algebraic decision tree model, element distinctness reduces to it, and element distinctness needs Ω(nlog⁡n)\Omega(n\log n)
  3. The sweep visits 2n2n events and each costs log⁡n\log n
  4. It is not a lower bound; a hash map gives O(n)O(n) for any input
Show the answer

B. In the algebraic decision tree model, element distinctness reduces to it, and element distinctness needs Ω(nlog⁡n)\Omega(n\log n)

Degenerate intervals [xi,xi][x_i,x_i] overlap exactly when two numbers coincide. The bound holds in the algebraic decision tree model; with small integer coordinates a difference array is linear.

Question 4

When is the Bentley–Ottmann sweep, O((n+k)log⁡n)O((n+k)\log n) for kk crossings, asymptotically slower than testing all (n2)\binom{n}{2} pairs?

  1. Never: a sweep always beats brute force
  2. When k=O(n)k=O(n)
  3. When k=Θ(n2)k=\Theta(n^2), since it then costs Θ(n2log⁡n)\Theta(n^2\log n)
  4. When segments are vertical
Show the answer

C. When k=Θ(n2)k=\Theta(n^2), since it then costs Θ(n2log⁡n)\Theta(n^2\log n)

With quadratically many crossings the sweep pays log⁡n\log n per crossing, while brute force pays O(1)O(1) per pair. Chazelle and Edelsbrunner's O(nlog⁡n+k)O(n\log n+k) algorithm removes that factor.

Further reading

  • R. L. Graham, D. E. Knuth & O. Patashnik, Concrete Mathematics, 2nd ed. (Addison-Wesley, 1994), §2.6, "Finite and infinite calculus".
  • J. L. Bentley & T. A. Ottmann, "Algorithms for reporting and counting geometric intersections," IEEE Transactions on Computers C-28(9) (1979), 643–647.
  • B. Chazelle & H. Edelsbrunner, "An optimal algorithm for intersecting line segments in the plane," Journal of the ACM 39(1) (1992), 1–54.
  • T. M. Chan, "Klee's measure problem made easy," Proceedings of FOCS (2013), 410–419.
  • M. de Berg, O. Cheong, M. van Kreveld & M. Overmars, Computational Geometry: Algorithms and Applications, 3rd ed. (Springer, 2008), chapter 2.