From 68d66aaa48d4f8c603c23f68cf106c2be8fa1303 Mon Sep 17 00:00:00 2001 From: Melove Gupta Date: Mon, 27 Oct 2025 12:34:51 +0530 Subject: [PATCH] Create running_sum_1d_array --- Python/algorithms/arrays/running_sum_1d_array | 46 +++++++++++++++++++ 1 file changed, 46 insertions(+) create mode 100644 Python/algorithms/arrays/running_sum_1d_array diff --git a/Python/algorithms/arrays/running_sum_1d_array b/Python/algorithms/arrays/running_sum_1d_array new file mode 100644 index 00000000..88e30130 --- /dev/null +++ b/Python/algorithms/arrays/running_sum_1d_array @@ -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})")