Running Array Sum
This post is part of the Algorithms Problem Solving series.
Problem description
This is the Running Array Sum problem. The description looks like this:
Given an array nums
. We define a running sum of an
array as runningSum[i] = sum(nums[0]…nums[i])
.
Return the running sum of nums
.
Examples
Input: nums = [1,2,3,4]
Output: [1,3,6,10]
Input: nums = [1,1,1,1,1]
Output: [1,2,3,4,5]
Input: nums = [3,1,2,10,1]
Output: [3,4,6,16,17]
Solution
The idea here is to cache the sum of the numbers while iterating through the list. For each number, add to the sum and then add the sum to the result list.
def running_sum(nums):
sum = 0
result = []
for num in nums:
sum += num
result.append(sum)
return result
Resources
- Learning Python: From Zero to Hero
- Algorithms Problem Solving Series
- Stack Data Structure
- Queue Data Structure
- Linked List
- Tree Data Structure
Have fun, keep learning, and always keep coding!