-
Notifications
You must be signed in to change notification settings - Fork 278
Expand file tree
/
Copy pathrunning_sum_1d_array
More file actions
46 lines (34 loc) · 1004 Bytes
/
running_sum_1d_array
File metadata and controls
46 lines (34 loc) · 1004 Bytes
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
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})")