Running Sum of 1d Array

Bryam Vicente
3 min readMay 25, 2021

For this blog, I’ll be going over another popular problem on LeetCode. Note that I’ll be using JavaScript to solve this problem! Here’s the prompt:

In other words, the question is asking us to create a function that takes in an array nums and returns an array with the running sums. The examples on the picture above do a great job showing what the inputs and outputs should be for this problem. Example 1 is showing how the output should be an array of results that depend on the input array. For example, my input is [1,2,3,4] and my output would be the results after adding 1 + 2, 1 + 2 + 3, 1 + 2 + 3 + 4. You can also notice how the first element inside of the output array is also the first element for the input array! So let’s begin!!

To start off, I’m not going to create a variable because it’s not needed and it’s good to save some space. Instead, I’ll go straight into creating a for loop. Here’s what the code looks like so far:

I’m starting from 1 instead of 0 because if we look at the examples, we should be able to recognize that the addition happens after the first element (nums[i]).

Since the for loop will be checking each element inside of nums, we need to figure out a way in which we can add the elements as the iteration takes place. I’ll leave a console.log(nums[i]) inside of the for loop to show what’s happening during the iteration. This is what nums[i] looks like inside the for loop when using the sample input on line 9 from the picture above:

All we have to do now is figure out a way in which we can replace the elements 2, 3, and 4 and instead have the results when adding 1 + 2, 1 + 2 + 3, and 1 + 2 + 3 + 4. For that we’re going to have to mutate the array by changing the value of nums[i]. The new value of nums[i] should be the addition of the current number being iterated (nums[i]) plus the numbers that were previously iterated. Here’s what the code looks like so far:

I placed a console.log() on line 7 so that we can see the new value for nums[i]. Here’s the new value for nums[i]:

These are the numbers that I was expecting which means that the logic worked! Now, the only part that’s missing is simply returning the mutated nums array.

Here’s the full solution along with multiple test cases:

Here are the results for lines 9–11:

Finally, here are the results on LeetCode:

I hope this blog was helpful in any way! For more info on for loops, checkout the resource section below!

Resources:

Sign up to discover human stories that deepen your understanding of the world.

Free

Distraction-free reading. No ads.

Organize your knowledge with lists and highlights.

Tell your story. Find your audience.

Membership

Read member-only stories

Support writers you read most

Earn money for your writing

Listen to audio narrations

Read offline with the Medium app

No responses yet

Write a response