DevPath

← All problems

Running Sum of an Array

Easy arrays · prefix-sum

Description

Return the running sum where result[i] is the sum of the first i+1 elements.

Constraints

1 <= n <= 100000

Examples

Input: nums = [1,2,3,4]

Output: [1,3,6,10]

Hints (1)
  • Each element is the previous running total plus the current value.

Solutions

Accumulate as you iterate. · Time O(n) · Space O(n)

func runningSum(nums []int) []int {
    out := make([]int, len(nums))
    sum := 0
    for i, n := range nums {
        sum += n
        out[i] = sum
    }
    return out
}

Create a free account to submit solutions, track progress and save problems.

Create account