Difference Array & Line Sweep
O(n log n)
Mark +1 at each start and −1 just past each end, then sweep a prefix sum to get the value at every position.
0/19 solved
Recognise it
The signal
Many range-add updates with reads only at the end, or max overlap at a point: bookings, car pooling, calendars, flowers in bloom.
1Brute force
Apply each range update cell by cell: O(n*q).
2The observation
Per-cell writes: each update touches two endpoints, one prefix sum materialises all.
3Why it works
Put +v at l and -v at r+1; after the prefix-sum pass, value at x equals the sum of all ranges covering x.
Reach for it when
- +Many range increments then read the final array — bookings, range additions, heat maps.
- +Count overlaps at a point / max concurrency — car pooling, meeting density, +1/−1 events.
- +Coordinates are large or online → line sweep over sorted boundary events.
Not when
- ×Range-sum queries on a static array with no updatesuse Prefix sum
- ×Updates and queries interleaved onlineuse Fenwick on the diff array, or lazy segment tree
- ×Operation isn't additive (range assign, range max) or you need range max onlineuse Segment tree with lazy propagation
- ×Coordinates up to 1e9use Coordinate compression or a sorted map sweep
- ×You need which intervals overlap or the merged shapes, not just how manyuse Merge intervals
Intuition
A difference array is the inverse of a prefix sum, and it makes "add a value to every element in range [l, r]" cost O(1) instead of O(r−l). The idea: instead of touching every cell, you record only where the change starts and where it stops.
Read the full intuition
To add v to [l, r] (inclusive): do diff[l] += v and diff[r+1] -= v. After all updates, take a prefix sum of diff and you get the final array. The +v "turns on" at l and the -v "turns it back off" just past r — like flipping a light on at l and off at r+1; the prefix sum is "is the light on here, and how bright."
This is the engine behind range increments (Corporate Flight Bookings), counting overlaps at a point (Car Pooling — +passengers at start, −at end), and calendar/booking problems. When coordinates are huge or you need the maximum concurrency, the same idea becomes a line sweep: make a (+1 at start, −1 at end) event per interval, sort by position, and sweep a running counter.
Why it costs what it costs
Time O(n + q). each of q updates is O(1); one O(n) prefix-sum pass builds the result. Line sweep is O(q log q) for the sort.
Space O(n). the difference array (or O(q) boundary events for the sweep).
Practice
- Range AdditionFoundationFoundationPremiumMedium
- Corporate Flight BookingsApply it · Same idea with 1-indexed inclusive bookings.Apply itAmazon, CitadelMedium
- Car PoolingOne change · Check a capacity limit at every point.One changeUber, LyftMedium
- Range Addition IITwists · All updates start at (0,0).TwistsEasy
- Maximum Population YearBranches · Events are births/deaths over years.BranchesEasy
- My Calendar IIBranches · Online bookings rejecting triple overlaps.BranchesMedium
- Number of Flowers in Full BloomCombine · Huge coordinates and point queries.CombineHard
- My Calendar IIIAdvanced · Report max concurrent bookings after each insert.AdvancedGoogle, CitadelHard
- The Skyline ProblemMastery checkMastery checkGoogle, AmazonHard
- Restaurant CustomersCSESMedium
- Range Update QueriesCSESMedium
- Counting PathsCSESMedium
Pitfalls
Classic bugs
- !Off-by-one at
r+1: size the arrayn+1sodiff[r+1]stays in bounds; discard the guard cell. - !Inclusive
[l,r]decrements atr+1; half-open[l,r)decrements atr. Mixing them shifts everything by one. - !Sweep ties: for half-open intervals process ends before starts at the same coordinate (after, if touching counts as overlap).
- !Forgot the final prefix-sum pass: the diff array itself is not the answer.
- !Many large updates overflow 32-bit; use 64-bit accumulators.
- !Naive per-range loop is O(updates x rangeLen), about 1e10 at 1e5 x 1e5: TLE.
Looks like it, isn't
- Range Addition II needs Invariants & Parity Arguments
Why
Every operation covers the top-left rectangle, so the maximum count sits in the min(a) x min(b) corner. No array is needed. source ↗ - My Calendar I needs Ordered Set / Balanced BST (TreeMap, multiset)
Why
One overlap check per insertion: compare with the floor and ceiling neighbours in a sorted structure. source ↗
Go deepervariants and techniques · 5 combinations · interviewer follow-ups · resources
Variants and techniques
- Sweep Line (events + active set)Sort start/end events by coordinate and process them in order while an active-set structure (counter, heap, ordered set, segment tree) tracks what is open.
- Batched range add+v at l, −v at r+1, prefix-sum once. Corporate Flight Bookings, Range Addition.
- Overlap counting+1 at start, −1 at end, prefix-sum or sweep; check a capacity. Car Pooling.
- Max concurrency (sweep)Sort +1/−1 events, track the running peak. My Calendar II/III, Number of Flowers in Full Bloom.
- Coordinate compressionMap sparse large coordinates to indices, then diff/sweep. Maximum Population Year (small range → direct).
- 2-D differenceFour-corner updates on a grid, 2-D prefix sum. Range-add to submatrices.
Combinations
Difference Array & Line Sweep+Coordinate Compression
concurrency/overlap counts with huge time values
- Difference Array & Line Sweep:
- range add as two point events
- Coordinate Compression:
- maps 1e9 coordinates to dense indices
Sweep Line (events + active set)+Top-K Elements
skyline / max active value over time
- Sweep Line (events + active set):
- processes building edges in x order
- Top-K Elements:
- max-heap (with lazy deletion) of active heights
Sweep Line (events + active set)+Segment Tree / Fenwick (BIT)+Coordinate Compression
area/perimeter of union of rectangles
- Sweep Line (events + active set):
- moves over x events
- Segment Tree / Fenwick (BIT):
- maintains covered length on y with range add
- Coordinate Compression:
- maps y endpoints to segment tree leaves
Sweep Line (events + active set)+Segment Tree / Fenwick (BIT)
count intersections of axis-parallel segments, or points dominated by a query in 2D, offline
- Sweep Line (events + active set):
- process vertical segments and horizontal endpoints in x order
- Segment Tree / Fenwick (BIT):
- a BIT over y counts the active horizontals in [y1, y2]
Greedy+Difference Array & Line Sweep
minimum number of fixed-length range flips/increments to reach a target
- Greedy:
- the leftmost position that needs a flip/increment must be handled now
- Difference Array & Line Sweep:
- records where the effect of each applied operation ends, giving O(1) per position
Minimum Number of K Consecutive Bit FlipsMinimum Number of Increments on Subarrays to Form a Target Array
Follow-ups interviewers ask
- 01What if updates and point queries interleave online? → a difference array needs a full rebuild each time; switch to a Fenwick tree (range-update/point-query form).
- 02What if coordinates are up to 1e9? → you can't allocate the array; coordinate-compress or use an ordered-map line sweep.
- 03What if the operation is range-assign or range-max, not add? → differences don't compose; use a segment tree with lazy propagation.
- 04What if it's 2-D (add to a submatrix)? → a 2-D difference array with four corner updates and a 2-D prefix sum.
State table
| op | diff after | meaning |
|---|---|---|
start: [0,0,0,0,0] |
— | n=4 (+1 guard) |
| +10 to [1,3] | [0,10,0,0,-10] |
turn +10 on at 1, off past 3 |
| +5 to [0,2] | [5,10,0,-5,-10] |
turn +5 on at 0, off past 2 |
| prefix-sum → | [5,15,15,10] |
final array (drop the guard) |