Running Sum of 1d Array
Difficulty: Easy · Pattern: Prefix Sum · LeetCode #1480
Return the running sum of nums: out[i] = nums[0] + … + nums[i].
Examples
text
[1, 2, 3, 4] → [1, 3, 6, 10]
[3, 1, 2, 10, 1] → [3, 4, 6, 16, 17]Hints
- Each running sum is the previous one plus the current element.
Approach
Accumulate left to right. This is the prefix-sum array (without the leading 0) that powers every range-sum trick in this pattern.
Complexity
Time: O(n). Space: O(n) for the output.
Python solution
def runningSum(nums):
out, s = [], 0
for x in nums:
s += x
out.append(s)
return outJavaScript solution
function runningSum(nums) {
let s = 0;
return nums.map((x) => (s += x));
}