Running Sum of 1d Array

Easy

Topics
ArrayPrefix Sum

Given an array nums, return its running sum where runningSum[i] = sum(nums[0..i]).

Example 1

nums1234
running13610
This prefix-sum row is the building block behind the range-query and subarray-sum problems.
Top row is the input; below it its running total.
Input:  nums = [1,2,3,4]
Output: [1,3,6,10]

Example 2

nums11111
running12345
Input:  nums = [1,1,1,1,1]
Output: [1,2,3,4,5]

Constraints

  • 1 <= nums.length <= 1000
  • -10^6 <= nums[i] <= 10^6
Editorial — intuition, approach, complexity and pitfalls

Intuition

Each output element is the sum of everything up to and including its position. Recomputing that sum per index is O(n^2); carrying it forward makes each step a single addition.

Worth noting that the output array is the result, not working memory, so the auxiliary space is O(1) by the usual convention. If the problem permits mutating the input — and this one does — you can write the running sum back into nums itself and allocate nothing at all.

Approach

  1. Keep a running total; append it at each position.

In place: nums[i] += nums[i-1] for i from 1.

Dry Run

nums = [1,2,3,4]

x=1   total 1    out [1]
x=2   total 3    out [1,3]
x=3   total 6    out [1,3,6]
x=4   total 10   out [1,3,6,10]

in place:  [1, 1+2=3, 3+3=6, 6+4=10]  -> same

Complexity

  • Time — O(n): one addition per element, against O(n^2) for recomputing each prefix.
  • Space — O(1) auxiliary: the returned array is the answer rather than scratch space. The in-place variant allocates nothing whatsoever.

Common Pitfalls

  • Recomputing sum(nums[:i+1]) per index, which is the quadratic version and looks deceptively tidy.
  • Starting the in-place loop at index 0, which reads nums[-1] and in Python silently wraps to the last element.
  • Calling the output O(n) auxiliary space. It is the result; the distinction matters when an interviewer asks whether you can do better.

Full Solution — all languages

class Solution:
    def runningSum(self, nums):
        total = 0
        out = []
        for x in nums:
            total += x
            out.append(total)
        return out
SensAI
Beta
Tap the mic to stop voice mode