Running Sum of 1d Array
Easy
Topics
Given an array nums, return its running sum where runningSum[i] = sum(nums[0..i]).
Example 1
nums
running
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
nums
running
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
- 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] -> sameComplexity
- 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 outimport java.util.*;
class Solution {
public int[] runningSum(int[] nums) {
int[] out = new int[nums.length];
int total = 0;
for (int i = 0; i < nums.length; i++) {
total += nums[i];
out[i] = total;
}
return out;
}
}#include <bits/stdc++.h>
using namespace std;
class Solution {
public: vector<int> runningSum(vector<int>& nums) {
vector<int> out(nums.size());
int total = 0;
for (size_t i = 0; i < nums.size(); i++) {
total += nums[i];
out[i] = total;
}
return out;
}
};/**
* @param {number[]} nums
* @return {number[]}
*/ var runningSum = function(nums) {
const out = [];
let total = 0;
for (const x of nums) {
total += x;
out.push(total);
}
return out;
};