easy

Running Sum of 1d Array

Return a new array where each element is the sum of all elements up to that point.

1. Define the problem

Running Sum of 1d Array

Given an array nums, return its running sum , where runningSumi = sum(nums0…numsi) . Keep a single running total as you walk the array once, appending it after every element instead of re-adding everything up to that point each time.

Constraints

  • 1 ≤ nums.length ≤ 1000
  • -106 ≤ numsi ≤ 106

Example

Inputnums = [1, 2, 3, 4]
Output[1, 3, 6, 10]

Explanation Running sum is obtained as [1, 1+2, 1+2+3, 1+2+3+4] = [1, 3, 6, 10].

2. Know the words first

In plain terms

Running total
A sum that keeps growing as you add each new value, without ever being recalculated from scratch.
3. Visualize the solution

Add each value onto the running total

Add each value onto the running total
Statusinit

total=0. Add nums[0]=1 → total=1. Record 1.

What happens in this step

total = 0
total += nums[0] = 0 + 1 = 1
result = [1]
Step 1 of 4

Steps to visualize

  1. Start a running total at 0.
  2. Walk the array from left to right.
  3. At each index, add that value onto the running total and record it.
  4. The recorded values, in order, are the running sum array.
4. Walk through the code

Walk through the code

Same walkthrough, now with the code. Press Next to move one step and watch which lines run.

Add each value onto the running total
Statusinit

total=0. Add nums[0]=1 → total=1. Record 1.

What happens in this step

total = 0
total += nums[0] = 0 + 1 = 1
result = [1]
Step 1 of 4
5. Solution

Solution

solution.tsTypeScript
function runningSum(nums) {
  const result = [];
  let total = 0;

  for (const value of nums) {
    total += value;
    result.push(total);
  }

  return result;
}
Time
O(n)
Space
O(n)
6. Test cases

Test cases

InputExpectedCovers
nums = [1, 2, 3, 4][1, 3, 6, 10]example from the docstring
nums = [1, 1, 1, 1, 1][1, 2, 3, 4, 5]every value the same, total climbs by one each step
nums = [3, 1, 2, 10, 1][3, 4, 6, 16, 17]varied magnitudes accumulating correctly
nums = [5][5]smallest valid input, a single element
nums = [-1, 2, -3, 4][-1, 1, -2, 2]negative values mixed with positive ones
nums = [0, 0, 0][0, 0, 0]every value is zero, running sum stays zero