Sponsored
Sponsored
This approach involves iterating through the array nums
and calculating the running sum iteratively. Use an accumulator variable to keep the sum of elements encountered so far, and place this running sum into the result array.
Time Complexity: O(n) where n is the number of elements in the array.
Space Complexity: O(1) since we're modifying the array in place.
1def runningSum(nums):
2 result = []
3 sum = 0
4 for num in nums:
5 sum += num
6 result.append(sum)
7 return result
8
9nums = [1, 2, 3, 4]
10result = runningSum(nums)
11print(result)
This Python function runningSum
uses a for loop to iterate through the list nums
, updating the sum
and appending the running total to the result
list, which is output at the end.
For the in-place approach, iterate through the array nums
, and update each position directly to the running sum. This method reduces space usage by avoiding the creation of a separate result array.
Time Complexity: O(n)
Space Complexity: O(1) since only the input array is modified.
1import
In this Java implementation, the running sum is calculated directly within the input array, reducing the need for additional space.