Algorithmsrunning sum

Running Sum (Cumulative Sum Calculation in Arrays)

TT
Testlaa Team
May 14, 20262 min read

Running sum is the streaming view of prefix sums: update total += x as elements arrive—perfect for online dashboards, sensor pipelines, and single-pass constraints.

Why this shows up in the real world

Live sports scores update running totals; broadcast APIs push deltas but UIs often show cumulative season points. Inventory scanners at checkout maintain a running count of items in the cart. Carbon accounting pipelines accumulate emissions as new invoices stream in.

Core idea (explained for students)

Initialize s = 0. For each incoming x, update s += x and emit or compare s. If modulo arithmetic, reduce after each add. If you need history, append s to a list—now you have an explicit prefix array. Space–time tradeoff: O(1) memory if only the latest total matters.

Try this in Python

def running_totals(values: list[int]) -> list[int]:
    s, out = 0, []
    for x in values:
        s += x
        out.append(s)
    return out


print(running_totals([1, 2, 3, 4]))

Common mistakes

  • Resetting the accumulator accidentally inside a nested loop.
  • Comparing running sums across different partitions of the stream without tagging segments.
  • Floating drift—prefer integer minor units (cents) for money.

Key takeaways

  • Running sum = prefix sum in action.
  • Great when data is too large to store entirely.
  • Log intermediate totals when debugging streaming bugs.

Tags:

Prefix & differencePythonStudents