Skip to main content

Running Sum of 1d Array

Problem Description​

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.

Examples​

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].

Complexity Analysis​

*** Time Complexity:** O(n)O(n)

*** Space Complexity:** O(n)O(n)

Constraints​

  • 1<= nums.length <= 1000
  • 10^6 <= nums[i] <= 10^6

Solution​

Approach​

The approach involves creating a result array of the same length as the input array, initialized to 1. We maintain a cumulative sum variable (sum1) that starts at 0. As we iterate through the input array, we update each element of the result array to be the current element plus the cumulative sum, then update the cumulative sum by adding the current element. This process ensures that each element in the result array represents the running sum of the input array up to that point.

Code in Different Languages​

Written by @ImmidiSivani
class Solution {
public:
std::vector<int> runningSum(std::vector<int>& nums) {
std::vector<int> res(nums.size(), 1);
int sum1 = 0;
for (int i = 0; i < nums.size(); ++i) {
res[i] = nums[i] + sum1;
sum1 += nums[i];
}
return res;
}
};

References​