DEV Community

Cover image for Algorithms Problem Solving: Running Array Sum
TK
TK

Posted on • Originally published at leandrotk.github.io

4

Algorithms Problem Solving: 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]
Enter fullscreen mode Exit fullscreen mode

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
Enter fullscreen mode Exit fullscreen mode

Resources

Hostinger image

Get n8n VPS hosting 3x cheaper than a cloud solution

Get fast, easy, secure n8n VPS hosting from $4.99/mo at Hostinger. Automate any workflow using a pre-installed n8n application and no-code customization.

Start now

Top comments (0)

AWS Security LIVE!

Join us for AWS Security LIVE!

Discover the future of cloud security. Tune in live for trends, tips, and solutions from AWS and AWS Partners.

Learn More

👋 Kindness is contagious

Please leave a ❤️ or a friendly comment on this post if you found it helpful!

Okay