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
nums = [1, 2, 3, 4][1, 3, 6, 10]Explanation Running sum is obtained as [1, 1+2, 1+2+3, 1+2+3+4] = [1, 3, 6, 10].
In plain terms
- Running total
- A sum that keeps growing as you add each new value, without ever being recalculated from scratch.
Add each value onto the running total
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]
Steps to visualize
- Start a running total at 0.
- Walk the array from left to right.
- At each index, add that value onto the running total and record it.
- The recorded values, in order, are the running sum array.
Walk through the code
Same walkthrough, now with the code. Press Next to move one step and watch which lines run.
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]
Solution
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)
Test cases
| Input | Expected | Covers |
|---|---|---|
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 |