Python coding

Counters after many range updates

A row of n counters starts at zero. Each update is a triple [start, end, delta] that adds delta to every counter from index start through end, both included. Return the list of counters after all the updates.

n >= 1, 0 <= start <= end < n, and delta may be negative. Ranges can be long, so touching every counter of every range is too slow: aim for O(n + u) with u updates.

Besides the tests, one large input (4,000 counters, 4,000 updates) with a ~200 ms limit (scaled to your device's speed): brute force won't pass.

  • apply_updates(6, [[0,2,5],[1,4,-2],[3,5,1]]) → [5,3,3,-1,-1,1]
  • apply_updates(4, [[0,3,1],[0,3,1],[3,3,10]]) → [2,2,2,12]
  • apply_updates(3, []) → [0,0,0]
Ctrl/⌘ + Enter runs · Tab indents
Hint 1

Do not walk each range. An update changes the level in only two places: where it begins and just after it ends.

Hint 2

Keep a difference array: diff[start] += delta and diff[end + 1] -= delta. A running sum over diff gives every counter's final value.

Hint 3

The trap is the right edge: cancel at end + 1, not end, and give diff one extra slot so an update that reaches the last counter stays in bounds.

Solution and why it works
pythonO(n + u), u = number of updates · O(n)
def apply_updates(n: int, updates: list[list[int]]) -> list[int]:
    diff = [0] * (n + 1)                 # diff[i] = counter i minus counter i - 1
    for start, end, delta in updates:
        diff[start] += delta
        diff[end + 1] -= delta           # the spare slot absorbs end == n - 1
    counters, level = [], 0
    for i in range(n):
        level += diff[i]
        counters.append(level)
    return counters

A difference array stores how much each counter differs from the one before it. Adding delta to a whole range changes only two of those differences: +delta where the range starts and -delta just past its end. Each update is O(1), and one prefix sum at the end rebuilds the counters. The trap is the right edge: cancel at end + 1, not end, and keep one spare slot so a range that reaches the last counter stays in bounds.