Running Sum of 1d Array

Michael Takeuchi
2 min readJan 2, 2021

We are going to work through a problem on LeetCode #1480 Running Sum of 1d Array. Given an array, each number equals the previous numbers in the array, returning the running sum when done. An example they give is:

Input: nums = [1,2,3,4]
Output: [1,3,6,10]
Explanation: Running sum is obtained as follows: [1, 1+2, 1+2+3, 1+2+3+4].

We will solve this in two very similar ways, with one utilizing the map method and the other using a for loop.

nums = [1,2,3,4]let sum = 0;
return nums.map(num => sum += num);
#=> [1,3,6,10]

Utilizing the map method, we can pass a callback to each element in the nums array. So first assigning a variable sum to keep count of our running total, we will start at 0. For each number in the array, we will add the sum variable with the current number. So walking through the example, we start at 1. We add 0 + 1, which equals 1. This becomes the number at nums[0] #=> [1] . Next moving to 2, we add 1 + 2, equaling 3. This becomes nums[1], with the result becoming [1,3]. We continue this for the length of the array adding each number to the sum. Next way we will go with a simple for loop.

nums = [1,2,3,4]for(var i=1;i<nums.length;i++) {             
nums[i]=nums[i]+nums[i-1];
}

return nums;
#=> [1,3,6,10]

Using the same nums array from before we will then go through the array starting at index of 1. We will start our loop at nums[1], because nums[0] will be the current sum. For each number in the array, we will add the current number with the previous number, and assign the current number to the new total. So unlike the previous example of using map and keeping a running sum count, we just add the current and previous numbers, since the previous number should be the current total.

--

--