Skip to content
  • Dashboard
  • Review
  • Go: plan & chat
  • Roadmap
  • Patterns & lessons49
  • Sheets
  • Problems1.5k
  • Ascend
  • Toolkit
  • Core CS + SQL
  • System Design
  • Machine Coding
  • Interview hub
  • Mock interview
  • Companies & OA
  • Leaderboard
  • Battles
  • College Cup
  • People

Keep your progress

Sync across devices with a free account.

Sign upSign in
Patterns & lessons
Sign inSign up
Patterns/Arrays & Two Pointers/Difference Array & Line Sweep

Learn the pattern · ~15 min

Difference Array & Line Sweep

also called difference array, range add point query, event counting

Write each range update as +v where it starts and −v just after it ends; one running sum at the end turns those marks into every position's value.

Signalsmany range-add updates, queries only after all updatesmaximum overlap / concurrency countbookings, car capacity, flowers in bloomLearn firstPrefix Sum
Cheat sheet and practice

Reach for it when you read

  • +Many updates of the form "add v to every element from l to r", and you need the final array once.
  • +Intervals whose effects stack: passengers in a car, people alive in a year, bookings per flight.
  • +"The most overlapping at any point": +1 at each start, −1 after each end, and the max of the running sum.
  • +Your brute force loops over every index of every range, q × n work.

Not this one when

  • ×Range sums asked on an array that doesn't change: a prefix sum. That's the reverse direction.
  • ×Updates and queries interleaved: a Fenwick or segment tree, because each read would need a fresh sweep.
  • ×Merge overlapping intervals into blocks, with no counts: sort by start and merge.

Learn Difference Array & Line Sweep

First, what is a "difference"?

Write down how much each element changes from the one before it. For a = [2, 2, 5, 5, 1]:

i 0 1 2 3 4
a[i] 2 2 5 5 1
change from the left neighbour 2 0 3 0 −4

That second row is the difference array: diff[i] = a[i] − a[i − 1], with diff[0] = a[0]. Nothing is lost. Run a running sum over it (2, 2 + 0, 2 + 0 + 3, …) and you get a back: 2, 2, 5, 5, 1.

Why bother? Add 3 to positions 1..3, making a = [2, 5, 8, 8, 1]. Inside the range every neighbour moved up together, so their differences didn't change. Only two differences did: position 1 is now 3 higher than its left neighbour, and position 4 is now 3 lower than its left neighbour. A whole range update is two edits to diff.

How do we mark an update?

Start from six zeros and apply three updates, each "add v to every position from l to r" (0-based, both ends included). The rule:

Add v at l, where the range starts. Subtract v at r + 1, just after it ends.

The array diff gets n + 1 slots, here 7, so that r + 1 still has a place to go when r is the last index.

update what happens diff (indices 0..6)
start empty 0, 0, 0, 0, 0, 0, 0
add 2 to 1..3 +2 at 1, −2 at 4 0, 2, 0, 0, −2, 0, 0
add 1 to 0..4 +1 at 0, −1 at 5 1, 2, 0, 0, −2, −1, 0
add 4 to 3..5 +4 at 3, −4 at 6 (the spare slot) 1, 2, 0, 4, −2, −1, −4

Then one running sum over diff[0..5] turns the changes back into values:

i 0 1 2 3 4 5
diff[i] 1 2 0 4 −2 −1
running sum 1 3 3 7 5 4

So the final array is [1, 3, 3, 7, 5, 4]. Check index 3: it's inside all three ranges, 2 + 1 + 4 = 7. The running sum carries each +v forward until its −v cancels it.

The code for it

C++
vector<long long> diff(n + 1, 0);       // one spare slot for r + 1
for (auto [l, r, v] : ups) {            // 0-based, inclusive [l, r]
    diff[l] += v;
    diff[r + 1] -= v;
}
vector<long long> out(n);
long long running = 0;
for (int i = 0; i < n; i++) {
    running += diff[i];                 // the sweep: diff itself is not the answer
    out[i] = running;
}

You don't need to memorise this. It's the two tables: two marks per update, then one running sum.

Why does the −v go at r + 1 and not at r? Because r is still inside the range and must keep the +v. The value has to drop back after r. That holds for an inclusive range [l, r]. If a problem gives you a half-open range [l, r), where r itself is not included, the cancel goes at r. Read which one you have before writing the second mark.

Fine, but how does this help us?

The classic problem: Corporate Flight Bookings. There are n flights, numbered 1 to n. A booking [first, last, seats] reserves seats on every flight from first to last, inclusive. Return the total seats on each flight.

Take n = 6 with bookings [1, 3, 10], [2, 5, 20], [4, 6, 5]. By hand, for each flight, add up the bookings that cover it:

flight covered by seats
1 [1, 3, 10] 10
2 [1, 3, 10], [2, 5, 20] 30
3 [1, 3, 10], [2, 5, 20] 30
4 [2, 5, 20], [4, 6, 5] 25
5 [2, 5, 20], [4, 6, 5] 25
6 [4, 6, 5] 5

The answer is [10, 30, 30, 25, 25, 5].

The brute force

Do exactly that: for every booking, walk every flight it covers.

C++
vector<long long> out(n, 0);
for (auto& b : bookings)
    for (int f = b[0]; f <= b[1]; f++)
        out[f - 1] += b[2];

That's O(n·q) for q bookings: in the worst case every booking covers every flight. At LeetCode's limits, 2 × 10⁴ bookings and 2 × 10⁴ flights, that's 4 × 10⁸ additions, right at the edge of the time limit. With 10⁵ of each it's 10¹⁰. Time limit exceeded.

The one thought that fixes it

Stop at booking [2, 5, 20]. The brute force writes 20 into four flights: 2, 3, 4 and 5.

But look at the gaps between neighbours. Flight 2 now holds 20 more than flight 1. Flights 3, 4 and 5 went up by the same 20 as the flight before them, so those gaps didn't move. Flight 6 holds 20 fewer than flight 5. Out of all the gaps, only two changed.

So don't write the range. Record the two changed gaps, +20 at flight 2 and −20 after flight 5, and let one sweep at the end add everything up. That's the difference array from above. The only new detail is the numbering: flights are 1-based, so flight first sits at index first − 1, and "just after last" sits at index last.

C++
vector<long long> diff(n + 1, 0), out(n);
for (auto& b : bookings) {
    diff[b[0] - 1] += b[2];             // 1-based flights: first - 1
    diff[b[1]] -= b[2];                 // (last - 1) + 1
}
long long running = 0;
for (int i = 0; i < n; i++) {
    running += diff[i];
    out[i] = running;
}

Dry run

After the three bookings, diff = [10, 20, 0, −5, 0, −20, −5].

flight diff running = seats what happens
1 10 10 booking 1 starts
2 20 30 booking 2 starts
3 0 30 nothing changes
4 −5 25 booking 1 ends (−10), booking 3 starts (+5)
5 0 25 nothing changes
6 −20 5 booking 2 ends

The last −5 (booking 3 ending) lands in the spare slot and is never read. [10, 30, 30, 25, 25, 5], the same answer as the brute force.

Why it's O(n + q)

Count the work per booking: two writes, no matter how long its range. Then the sweep touches each flight once. So q bookings and n flights cost about 2q + n steps, O(n + q): about 6 × 10⁴ steps instead of 4 × 10⁸. Space is the n + 1 slots.

From O(n·q) down to O(n + q), by recording where things change instead of the things themselves.

One condition: all updates must come before the reads. If updates and questions are mixed, each question would need a fresh sweep: put the difference array in a Fenwick tree instead.

Half-open ranges? Car Pooling

In Car Pooling, a trip [people, from, to] puts people in the car at from, and they get out at to. At kilometre to they're already gone, so the range is half-open and the cancel goes at to, not to + 1.

C++
diff[from] += people;
diff[to] -= people;                     // they leave at `to`

Then sweep and fail as soon as the running sum goes over capacity. Trips [2, 1, 4], [3, 4, 7], [1, 2, 6] with capacity 4 peak at exactly 4 (at kilometre 4 the first group has just left and the second has just got in): the answer is true. Treat the ranges as inclusive and kilometre 4 holds 6, so the answer wrongly becomes false.

The busiest moment? Count with +1 and −1

Maximum Population Year gives birth and death years and asks for the year with the most people alive. Each person is a range: +1 at the birth year, −1 at the death year (they're not counted in the year they die, so again half-open). Sweep and keep the year where the running sum is largest.

Coordinates up to 10⁹? A sorted map

When positions are huge you can't allocate the array. Store only the change points in a map<int, long long>, which keeps them sorted, and sweep the map in order. Between two change points the running sum is constant. My Calendar II is this, with one sweep per new booking: fine at its 1,000 calls.

Remember this

  • Many "add v to every element from l to r" updates, then one read of the result: two marks per update, one running sum.
  • Size it n + 1, so r + 1 always has a slot.
  • Get the end right: inclusive [l, r] cancels at r + 1, half-open [l, r) at r. Convert 1-based input first.
  • Use long long: updates stack up.
  • Whenever a problem asks "after all these range updates, what's at each position?" or "how many overlap at the busiest point?", it's a difference array.

Practise it on Corporate Flight Bookings, then Maximum Population Year (count the overlap), Car Pooling (half-open, capacity check), My Calendar II (huge coordinates), Number of Flowers in Full Bloom (questions after the sweep) and Minimum Number of K Consecutive Bit Flips (flips as you go).

Below, watch Corporate Flight Bookings run line by line.

Watch it work, line by line

Corporate Flight Bookings ↗, n = 5, bookings = [[1,2,10], [2,3,20], [2,5,25]] → [10, 55, 45, 25, 25]. Step with → and ←. The data is on the left, the code and the variables that changed on the right, and 3 times it stops to ask you what happens next.

Loading the walkthrough…

When to use it, and when not

Ask yourself

Are there many "add v to a whole range" updates, and do I only need the values after all of them?

Reach for it when

  • +many range-add updates, queries only after all updates
  • +maximum overlap / concurrency count
  • +bookings, car capacity, flowers in bloom
  • +coordinates small enough for an array, or sortable events for a map

It fails 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

Looks like it, isn't (and the other way round)

  • Minimum Number of Increments on Subarrays to Form a Target Array looks like Segment Tree / Fenwick (BIT), needs this pattern

    Divide-and-conquer on the minimum works, but the editorial's difference-array view gives the sum of positive rises in O(n).

  • Range Addition II looks like Difference Array & Line Sweep, needs Invariants & Parity Arguments

    Every operation covers the top-left rectangle, so the maximum count sits in the min(a) x min(b) corner. No array is needed.

  • My Calendar I looks like Difference Array & Line Sweep, needs Ordered Set / Balanced BST (TreeMap, multiset)

    One overlap check per insertion: compare with the floor and ceiling neighbours in a sorted structure.

Why this pattern and not another

You apply many additive range updates and only need the result after all of them (or the peak overlap). Marking +v/−v boundaries makes each update O(1) and one prefix-sum pass reconstructs everything.

Recall card

Answer each one out loud before you open it. Come back in three days and try again without reading the page.

  • 1For an inclusive range [l, r], where do the two marks go?Reveal

    +v at l and −v at r + 1, which is why the array needs n + 1 slots.

  • 2What turns the difference array into the answer?Reveal

    A prefix sum (running total) from left to right. The diff array alone is just the changes.

  • 3When does a plain difference array stop working?Reveal

    When questions come between updates (use a Fenwick or lazy segment tree), or when positions are too big for an array (use sorted events).

Practice ladder

every problem →
  1. 1Maximum Population Yearcount the overlapEasy
  2. 2Corporate Flight Bookingsthe hookMedium
  3. 3Restaurant Customerssorted eventsMedium
  4. 4Car Poolingcapacity checkMedium
  5. 5My Calendar IIhuge coordinatesMedium
  6. 6Number of Flowers in Full Bloomquestions after the sweepHard
  7. 7Range Update Queriesupdates and queries mixedMedium
  8. 8Minimum Number of K Consecutive Bit Flipsflips as you goHard

Finished Difference Array & Line Sweep? Mark it done and Lessgo moves you to the next step.

Start the climb9 steps from E-Rank to S, with a coachPractise itthe cheat sheet and every problem, easy to OA level
Back to Difference Array & Line Sweep

On this page

The lessonWatch it workThe templateWhen to use itRecallPractice ladder
TodayReviewPatternsProblems

The template: frame and slot · every line explained, then clean C++, Java and Python to revise from

Start the free 7-day trial