DSA Factory
Free lessonsArrays · Stage 2 · Traversal with state · Step 3

Carry a total forward

Build the list of running totals. About 7 minutes.

A balance after every transaction

A bank statement doesn't just show your spending. Next to each transaction it shows your balance at that moment: the total of everything so far.

That's a running total. Walk through the array, keep adding each value to a total, and after every addition write the total down in a new list. You'll use this idea a lot later, for answering "what's the total between day 3 and day 7?" in one step.

Add, then write it down: one total per box.
The total so far
2
0
4
1
1
2
3
3
i

total = 2. result = [2]

Move 1 of 4

Add first, then record

Inside the loop, order matters. Add the current value to the total first, and only then write the total down.

Do it the other way round and every entry is one step behind: the first entry is 0, and the last value never gets counted. For 2, 4, 1 you want 2, 6, 7, not 0, 2, 6.

Record first? every entry is one step behind.
In code
total = 0
result = []
for x in nums:
    total += x
    result.append(total)
return result
Quick check

What are the running totals of 5, 1, 3?

  1. A5, 6, 9
  2. B0, 5, 6
  3. C5, 6, 4
Show the answer

5, 6, 9. 5, then 5 + 1, then 5 + 1 + 3.

Your problem

Running totals

Return a list of the same length where each entry is the sum of all values up to and including that position.

Example
nums = [2, 4, 1, 3] → [2, 6, 7, 10]

0 ≤ n ≤ 1,000 · −1,000 ≤ each value ≤ 1,000

Solve it in your browserPython, C++, Java or JavaScript. Hints if you get stuck. No sign-up needed.
Start coding