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.
1#include <vector>
2#include <iostream>
3
4std::vector<int> runningSum(std::vector<int>& nums) {
5 std::vector<int> result(nums.size());
6 int sum = 0;
7 for(int i = 0; i < nums.size(); i++) {
8 sum += nums[i];
9 result[i] = sum;
10 }
11 return result;
12}
13
14int main() {
15 std::vector<int> nums = {1, 2, 3, 4};
16 std::vector<int> result = runningSum(nums);
17
18 for(int num : result) {
19 std::cout << num << " ";
20 }
21 return 0;
22}
This C++ solution implements the runningSum
function which iterates through the input vector, accumulates the total in sum
, and assigns values to the result vector. The final result is printed in the main
function.
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.
1function
In this JavaScript solution, the running sum is computed directly on the input array, updating each element starting from the second position.