class Solution:
def runningSum(self, nums):
s = 0
n = len(nums)
prefix_sum = [0] * n
for i in range(n):
s += nums[i]
prefix_sum[i] = s
return prefix_sum
# Time: O(n)
# Space: O(n)
The running sum of a 1D array is a fundamental problem in array manipulation and prefix sum techniques. It involves creating a new array where each element at index i
contains the sum of all elements from index 0
to i
in the original array. This technique is widely used in many algorithmic problems, such as subarray sum queries, cumulative frequency analysis, and more.
Given an input array nums
, return a new array runningSum
such that runningSum[i] = nums[0] + nums[1] + ... + nums[i]
. This is equivalent to computing the prefix sum at each index in a single pass through the array.
The optimal approach for solving this problem is simple and highly efficient. You initialize a variable to track the cumulative sum as you iterate through the array. At each step, you add the current number to the cumulative sum and store the result in the corresponding index of the output array.
This one-pass strategy ensures optimal performance with minimal memory overhead. If modifying the input array is allowed, you can even compute the result in-place.
Let's say nums = [1, 2, 3, 4]
. The running sum array would be:
Final result: [1, 3, 6, 10]
The running sum is a core building block for more advanced algorithms like range sum queries, sliding window techniques, and dynamic programming. Mastering this pattern will help in optimizing solutions where repeated summation of ranges would otherwise lead to inefficient nested loops.
Solving the "Running Sum of 1D Array" problem efficiently demonstrates your understanding of array traversal and prefix sum optimization. This simple yet powerful concept is frequently tested in coding interviews and competitive programming.