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.
1function runningSum(nums) {
2 let result = [];
3 let sum = 0;
4 for (let num of nums) {
5 sum += num;
6 result.push(sum);
7 }
8 return result;
9}
10
11const nums = [1, 2, 3, 4];
12const result = runningSum(nums);
13console.log(result);
The JavaScript implementation employs a for...of loop to calculate the running sum by appending the current running total to the result array. The calculated running sums are logged to the console.
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.
1def
This Python function performs in-place modifications of nums
by using cumulative addition starting from the second position of the list.