Skip to content
Open
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
46 changes: 46 additions & 0 deletions Python/algorithms/arrays/running_sum_1d_array
Original file line number Diff line number Diff line change
@@ -0,0 +1,46 @@
from typing import List

def running_sum(nums: List[int]) -> List[int]:
"""
Compute the running sum of a 1D array.

Given an integer array nums, return the running sum such that:
running_sum[i] = nums[0] + nums[1] + ... + nums[i]

Time Complexity: O(n)
Space Complexity: O(n)

Args:
nums (List[int]): List of integers.

Returns:
List[int]: Running sum of the input list.

Example:
>>> running_sum([1, 2, 3, 4])
[1, 3, 6, 10]
"""
n = len(nums)
if n == 0:
return []

ans = [0] * n
ans[0] = nums[0]

for i in range(1, n):
ans[i] = ans[i - 1] + nums[i]

return ans


if __name__ == "__main__":
# quick test cases
examples = [
([1, 2, 3, 4], [1, 3, 6, 10]),
([1, 1, 1, 1, 1], [1, 2, 3, 4, 5]),
([3, 1, 2, 10, 1], [3, 4, 6, 16, 17]),
([], []),
]

for arr, expected in examples:
print(f"{arr} -> {running_sum(arr)} (expected {expected})")