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.
Example 1:
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].
Example 2:
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].
Example 3:
Input: nums = [3,1,2,10,1] Output: [3,4,6,16,17]
Constraints:
1 <= nums.length <= 1000-10^6 <= nums[i] <= 10^6This 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.
This C program uses a function runningSum which takes the original array nums, its size, and an array returnArr to store the running sums. An accumulator sum keeps track of the cumulative total as we iterate over the array.
C++
Java
Python
C#
JavaScript
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.
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.
In this C solution, the running sum is calculated in place by iterating over the array starting from the second element. Each element is updated as the sum of itself and its predecessor.
C++
Java
Python
C#
JavaScript
Time Complexity: O(n)
Space Complexity: O(1) since only the input array is modified.
| Approach | Complexity |
|---|---|
| Iterative Accumulation | Time Complexity: O(n) where n is the number of elements in the array. |
| In-Place Modification | Time Complexity: O(n) |
Running Sum of 1d Array | LeetCode 1480 | C++, Java, Python • Knowledge Center • 23,332 views views
Watch 9 more video solutions →Practice Running Sum of 1d Array with our built-in code editor and test cases.
Practice on FleetCode