Running Sum of 1d Array
📘 Problem Statement
You’re given an array nums
. You need to return a new array runningSum
such that:
runningSum[i] = sum(nums[0] + nums[1] + ... + nums[i])
🔍 Example
Example 1 Input:
nums = [1, 2, 3, 4]
Output:
[1, 3, 6, 10]
Explanation:
runningSum[0] = 1 runningSum[1] = 1 + 2 = 3 runningSum[2] = 3 + 3 = 6 runningSum[3] = 6 + 4 = 10
🛠️ Solution - Using Prefix Sum
The problem is the essential crux of Prefix Sum
. Idea is to loop through the original array and maintain a cumulative sum in a new array. Here is a quick implementation of the solution:
def runningSum(nums):
result = []
current_sum = 0
for num in nums:
current_sum += num
result.append(current_sum)
return result