LeetCode: Running Sum Of 1d Array Solution

Accumulate

Approach

Either mutate array by accumulate sum or calculate prefix sum

Implementation

1// approach 1: mutate the array
2var runningSum = function (nums) {
3 for (let i = 1; i < nums.length; i++) {
4 nums[i] += nums[i - 1]
5 }
6 return nums
7}
8
9// approach 2: prefix sum
10var runningSum = function (nums) {
11 const prefixSums = []
12 let sum = 0
13 for (const num of nums) {
14 sum += num
15 prefixSums.push(sum)
16 }
17 return prefixSums
18}

References

Original problem

Comments

Loading comments...

Tags

leetcode

array

Next Post

LeetCode: Kids With The Greatest Number Of Candies

HoningJS

Search Posts