Python 3D Academyবাংলা

Difference arrays: many range updates at once

🌍 In real life. A bus runs from Gabtoli through 8 stops. The conductor doesn't count everyone at every stop. He only notes changes: "5 got on at stop 0", "3 got off at stop 4". To know how many are on board at any stop, he keeps one running total of those changes. A group that rides 6 stops costs him two notes, not six.

That is a difference array: prefix sums, read backwards.

The idea in one sentence: to add v to every position in a range [on, off), write +v at diff[on] and -v at diff[off]; after all the updates, the running total of diff gives every position's value.

Its words:

  • range update: adding the same amount to every position in a range [on, off)
  • difference array: diff, which stores only where the value changes, and by how much
  • rebuild: the running total of diff, which gives every position's value

How it works, step by step:

  1. diff = [0] * (stops + 1) (one extra slot, for groups that ride to the last stop)
  2. for each group (on, off, people): diff[on] += people, diff[off] -= people
  3. walk the stops: load += diff[stop] is the number on board at that stop

Watch the + and − marks go into the diff row, then the loads rise stop by stop from one running total:

Why it is correct. The running total at stop s adds up diff[0..s]. A group (on, off, people) put +people at on and −people at off, so it adds people to every running total from on up to off − 1, and its two marks cancel from off on: exactly the stops it rides. Every group adds independently, so the totals are the sums of all groups on board.

What it costs, worked out. g groups and n stops:

  • adding every group to every stop it rides: up to g × n additions; 10,000 groups riding 1,000 stops is up to 10 million
  • the difference array: 2 marks per group plus one pass over the stops: 20,000 + 1,000

That is O(g + n) instead of O(g × n). The marks can come in any order; only the final pass needs them all.

def loads(stops, trips):
    diff = [0] * (stops + 1)
    for on, off, people in trips:
        diff[on] += people             # they start riding here
        diff[off] -= people            # and stop riding here
    out, load = [], 0
    for stop in range(stops):
        load += diff[stop]
        out.append(load)
    return out

print(loads(6, [(0, 3, 2), (1, 5, 3), (2, 4, 1)]))
print(max(loads(6, [(0, 3, 2), (1, 5, 3), (2, 4, 1)])) <= 5)   # fits a 5-seat van?

Mistakes and edge cases.

  • marking -people at off - 1 makes people leave a stop too early; in [on, off) the group is still on board at off - 1
  • a diff list of length stops breaks for groups that ride to the end (off == stops): make it one longer
  • reading diff itself as the answer: diff holds the changes; the loads are its running totals
  • the same trick works for any "add v to a range" job: discounts on days, paint on a wall, bookings on flights

Quiz

  1. What does this print?

    diff = [0] * 5
    for on, off, people in [(0, 2, 4), (1, 4, 1)]:
        diff[on] += people
        diff[off] -= people
    print(diff)
  2. Running totals of that diff, for stops 0 to 3: what does this print?

    diff = [4, 1, -4, 0, -1]
    load, out = 0, []
    for stop in range(4):
        load += diff[stop]
        out.append(load)
    print(out)
  3. Why does diff need one more slot than there are stops?

    • A group riding to the last stop marks −people at diff[stops]
    • Python lists need a spare slot
    • To store the total
  4. g groups, n stops. What does the difference array cost?

    • O(g + n)
    • O(g × n)
    • O(n²)
  5. loads(6, [(0, 3, 2), (1, 5, 3), (2, 4, 1)]) should be [2, 5, 6, 4, 3, 0], but this gives [2, 5, 6, 8, 9, 12]: nobody ever gets off. Which line is wrong?

    def loads(stops, trips):
        diff = [0] * (stops + 1)
        for on, off, people in trips:
            diff[on] += people
            diff[off] += people
        out, load = [], 0
        for stop in range(stops):
            load += diff[stop]
            out.append(load)
        return out

Coding tasks

  1. Write loads(stops, trips) in O(groups + stops) with a difference array: each trip is (on, off, people), riding stops on..off − 1. Give back how many are on board at each stop 0..stops − 1.

  2. Write fits(trips, seats): True if a van with seats seats can carry every trip (on, off, people) without ever having more than seats on board. Stops are 0 up to the largest off.