Skip to main content

1480 - Running Sum of 1d Array

Details

KeyValue
Linkhttps://leetcode.com/problems/running-sum-of-1d-array/
LanguagePython 3
Runtime50 ms, faster than 65.50% of Python3 online submissions for Running Sum of 1d Array
Memory Usage13.9 MB, less than 94.41% of Python3 online submissions for Running Sum of 1d Array
DatastructuresList[int]
Algorithmsiterate, sum, accumulate

Procedure

  1. TBD...

Code

Option 1: Iterate a Running Total in New List

    def runningSum(self, nums: List[int]) -> List[int]:
answer = []
running_total = 0

for num in nums:
running_total += num
answer.append(running_total)

return answer

Option 2: Iterate a Running Total in Place

    def runningSum(self, nums: List[int]) -> List[int]:
for i in range(1,len(nums)):
nums[i] += nums[i-1]
return nums

Option 3: One-Liner w/ Enumerate

    def runningSum(self, nums: List[int]) -> List[int]:
return [ sum(nums[:i]) for i, _ in enumerate(nums,1) ]

Option 4: One-Liner w/ Range/Len

    def runningSum(self, nums: List[int]) -> List[int]:
return [ sum(nums[:i+1]) for i in range(len(nums)) ]

Option 5: One-Liner w/ Built-In Accumulate Function

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