Given an array nums
. We define a running sum of an array as runningSum[i] = sum(nums[0]...nums[i])
.
Return the running sum of nums
.
For example:
Input: nums = [1,2,3,4] Output: [1,3,6,10] Explanation: Running sum is obtained as follows: [1, 1+2, 1+2+3, 1+2+3+4].
Input: nums = [1,1,1,1,1] Output: [1,2,3,4,5] Explanation: Running sum is obtained as follows: [1, 1+1, 1+1+1, 1+1+1+1, 1+1+1+1+1].
Input: nums = [3,1,2,10,1] Output: [3,4,6,16,17]
Constraints:
1 <= nums.length <= 1000
-10^6 <= nums[i] <= 10^6
The most straightforward approach is to iterate through the input array nums
. For each index i
, calculate the sum of elements from nums[0]
to nums[i]
. Store this sum in the runningSum
array at the corresponding index i
.
def runningSum_naive(nums):
n = len(nums)
running_sum = [0] * n
for i in range(n):
current_sum = 0
for j in range(i + 1):
current_sum += nums[j]
running_sum[i] = current_sum
return running_sum
The outer loop runs n
times, and the inner loop runs up to i+1
times in each iteration of the outer loop. Thus, the time complexity is O(n^2).
We use an additional array running_sum
of size n
to store the running sums. Therefore, the space complexity is O(n).
We can optimize the above approach by realizing that the running sum at index i
can be computed using the running sum at index i-1
. Specifically, runningSum[i] = runningSum[i-1] + nums[i]
. This avoids the inner loop in the naive approach.
def runningSum_optimal(nums):
n = len(nums)
running_sum = [0] * n
running_sum[0] = nums[0]
for i in range(1, n):
running_sum[i] = running_sum[i-1] + nums[i]
return running_sum
We iterate through the array nums
once. The time complexity is O(n).
We use an additional array running_sum
of size n
to store the running sums. Therefore, the space complexity is O(n).
It's possible to avoid using extra space. We can modify the original nums
array to store the running sum.
def runningSum_in_place(nums):
for i in range(1, len(nums)):
nums[i] += nums[i-1]
return nums
We iterate through the array nums
once. The time complexity is O(n).
We modify the input array in-place. Therefore, the space complexity is O(1).