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 events. Pushed into the plane, the same sweep finds every crossing among 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 range updates offline in .
- Add a degree- polynomial to a range with at most point updates on the -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 lower bound in the algebraic decision tree model.
- Explain the Bentley–Ottmann sweep, the optimal 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 , define the inclusive prefix sum and the backward difference :
In the course's prefix notation, .
Differencing a prefix sum leaves its last term:
Summing differences telescopes, and :
As matrices, is the lower-triangular matrix of ones, and its inverse has ones on the diagonal and just below it:
A range update adds times the indicator of , whose difference is two spikes (drop when ). By linearity, updates cost on , and one application of rebuilds in : in total, against up to for looping over each range.
Online, when reads arrive between updates, store in a Fenwick tree: a range update is two point updates, and reading is a prefix sum, each . 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 to , where . Its first difference is on all of , no longer sparse. But that is itself a range update plus one spike, so take the difference once more.
Let on and elsewhere. Its first difference:
Difference again. Only the three places where changes value survive:
So each ramp costs three point updates on , and two prefix passes rebuild the array:
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]Using third differences, at most how many point updates does adding a quadratic polynomial to one range require?
- 3
- 4
- 6
- 9
Show the answer
C. 6
With , the theorem allows up to nonzero cells at the left end, , and 3 at the right end, : at most . Three prefix passes then rebuild the array. (A particular quadratic can need fewer: needs only 2 at the left end, because already vanishes at .)
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:
Sweep lines: events instead of cells
With coordinates up to , a difference array indexed by coordinate is out of the question, but only the endpoints matter. Turn each half-open interval into two events, at and at , 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 time for sorting plus for the sweep.
Equivalently, compress the endpoints to ranks and use an ordinary difference array on the ranks.
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)])) # 2In the code above, suppose events at the same coordinate were processed starts first, then ends. What would it return for the half-open intervals ?
- 2
- 3
- 4
- 1
Show the answer
C. 4
At two meetings end and two begin. Starts first would count all four as running at once, , before the two endings are subtracted. Half-open intervals that touch at 11 never overlap, so the true answer is 2. Closed intervals 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 overlapping rectangles standing on a line, in . With a segment tree over compressed -coordinates that supports range addition and a global maximum, it finds the point covered by the most of rectangles in (see Lazy Propagation).
Sweeping the plane: Bentley–Ottmann and Klee
Shamos and Hoey (1976) decided whether any two of line segments intersect in 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 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 , is worse than testing all pairs. Chazelle and Edelsbrunner (1992) reached time, and Balaban (1995) the same time in space, matching the lower bound in the algebraic decision tree model: just to decide whether any crossing exists, and to write the output.
Sweeps also measure unions. Klee's measure problem (Klee, 1977) asks for the total length of a union of intervals: sort and sweep in , which Fredman and Weide (1978) proved optimal in the linear decision tree model. The area of a union of rectangles takes with a sweep and a segment tree that tracks the covered length of the sweep line (Bentley, 1977). In dimensions the best bound for boxes is , by Chan's (2013) strikingly simple divide and conquer, after Overmars and Yap's (1991).
Key takeaways
- Prefix summation and the backward difference are inverse linear maps; a range update is two spikes in , so offline updates cost .
- A degree- polynomial added to a range touches at most cells of , and 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 , optimal in the algebraic decision tree model; the tie rule depends on whether intervals are open or closed.
- Bentley–Ottmann reports segment crossings in ; is optimal; Klee's measure problem in dimensions sits at 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.
You add the ramp to , where , using an array of second differences. Which cells change?
- at and at
- at every cell of
- at and at
- at , at and at
Show the answer
D. at , at and at
The first difference of the ramp is on and at . Its difference is where it starts, at (from down to ), and at (from back to ).
A sweep computes the maximum number of simultaneously running meetings. Meetings are closed intervals , so one ending at 11 and one starting at 11 do overlap at time 11. At equal coordinates, which events must come first?
- Ends before starts
- Starts before ends
- Either order gives the same maximum
- 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 the rule flips.
Why is a lower bound for the maximum overlap of intervals?
- Every algorithm must sort the endpoints
- In the algebraic decision tree model, element distinctness reduces to it, and element distinctness needs
- The sweep visits events and each costs
- It is not a lower bound; a hash map gives for any input
Show the answer
B. In the algebraic decision tree model, element distinctness reduces to it, and element distinctness needs
Degenerate intervals overlap exactly when two numbers coincide. The bound holds in the algebraic decision tree model; with small integer coordinates a difference array is linear.
When is the Bentley–Ottmann sweep, for crossings, asymptotically slower than testing all pairs?
- Never: a sweep always beats brute force
- When
- When , since it then costs
- When segments are vertical
Show the answer
C. When , since it then costs
With quadratically many crossings the sweep pays per crossing, while brute force pays per pair. Chazelle and Edelsbrunner's 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.