Running Sum of 1d Array — LeetCode 1480 Python Solution

EasyArrayPrefix Sum
Problem
#1480
Pattern
Prefix Sum
Reading time
2 min

The problem

Given an array nums. We define a running sum of an array as runningSum[i] = sum(nums[0]…nums[i]).

Example

Input
nums = [1,2,3,4]
Output
[1,3,6,10]
Explanation
Running sum is obtained as follows: [1, 1+2, 1+2+3, 1+2+3+4].

Python solution

Python
class Solution:
    def runningSum(self, nums: List[int]) -> List[int]:
        return list(accumulate(nums))

Complexity

MeasureComplexity
TimeO(n), where n is the length of the array
SpaceO(1) auxiliary

Pattern: Prefix Sum

Precompute running totals once so any range query becomes a single subtraction. LeetCode 1480. Running Sum of 1d Array is filed here on both counts: the reference solution below belongs to the algorithm family this hub collects, and LeetCode tags it Prefix Sum.

The prefix sum guide has the Python template for the pattern and the 157 LeetCode problems that use it.

Related problems

Frequently asked questions

How hard is LeetCode 1480. Running Sum of 1d Array?
LeetCode 1480. Running Sum of 1d Array is rated Easy on LeetCode.
What is the time complexity of LeetCode 1480. Running Sum of 1d Array?
The Python solution on this page runs in O(n), where n is the length of the array.
What is the space complexity of LeetCode 1480. Running Sum of 1d Array?
The Python solution on this page uses O(1) auxiliary space.
What topics does LeetCode 1480. Running Sum of 1d Array cover?
LeetCode 1480. Running Sum of 1d Array is tagged Array and Prefix Sum on LeetCode.

Stuck on problems like this in a live interview?

Stealth Interview is a desktop app for macOS and Windows. It reads the problem off your screen and returns a working solution with a step-by-step explanation and its time and space complexity — invisible to screen sharing.

Get Stealth Interview