A solution to LeetCode Problem 1480: Running Sum of 1d Array in JavaScript
If you’re preparing for technical interviews or want to improve your coding skills, solving practice problems on LeetCode is a great way.
In this post, we’ll discuss a solution to the “Running Sum of 1d Array” problem on LeetCode.
Problem Description
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
.
Example 1:
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].
Example 2:
Input: nums = [1,1,1,1,1] Output: [1,2,3,4,5] Explanation: Running sum is obtained as follows: [1, 1+1, 1+1+1, 1+1+1+1, 1+1+1+1+1].
Example 3:
Input: nums = [3,1,2,10,1] Output: [3,4,6,16,17]
Constraints:
1 <= nums.length <= 1000
-10^6 <= nums[i] <= 10^6
Solution
To solve this problem, we can simply iterate through the array and keep a running sum of the elements. We can do this by declaring a variable sum and setting it to 0.
Then, for each element in the array, we add the element to sum and store the result in a new array.
Here is the solution in JavaScript:
function runningSum(nums) {
let sum = 0;
let result = [];
for (let num of nums) {
sum += num;
result.push(sum);
}
return result;
}
Let’s go through an example to see how this solution works.
Consider the input [1,2,3,4]. Our loop will start at i = 0, and the first iteration will have a num equal to 1. We add 1 to the sum and push the result, 1, to the result array.
On the next iteration, the num is 2 and the sum is 1. We add 2 to the sum and push the result, 3, to the result array.
The loop continues in this manner, updating sum and adding the result to the result array each time. When the loop is finished, result will be equal to [1,3,6,10], which is the running sum of the input array.
This solution has a time complexity of O(n), where n is the length of the nums array, since we only need to loop through the array once.
I hope this helps! Let me know if you have any questions or suggestions for improvement.