Skip to content

Edvins Antonovs

Running sum of 1d array code challenge

My approach to solving LeetCode’s Running sum of 1d array code challenge.


Problem

Given an array nums. We define a running sum of an array as runningSum[i] = sum(nums[0]…nums[i]).

Return the running sum of nums.

Solution

We start by creating a new temporary array (temp) and populating it with the first array's element (nums[0]). We need to do this, as below we start for loop, where during each iteration, we will be using the last temporary array value (temp[i - 1]) and sum it with the current's loop value (nums[i]). We will push the result of this addition to the temp array.

Finally, we return the temp array.

1var runningSum = function (nums) {
2 let temp = [nums[0]];
3
4 for (let i = 1; i < nums.length; i++) {
5 temp.push(temp[i - 1] + nums[i]);
6 }
7
8 return temp;
9};

Appendix

© 2024 by Edvins Antonovs. All rights reserved.