1480 Running Sum of 1d Array

Published:

Problem

Solution

Intuition

This problem requires us to return the running sum for each number in nums. The running sum is the sum of all preceding integers including the current integer.

We can solve this in-place by continously adding the value stored in the previous index with the current number.

Approach

  1. For each index in nums. Add the value stored in the previous index with the current index.
  2. Return nums.

Complexity

  • Time complexity: $O(n)$. We iterate through each number in nums and perform constant time operation on each iteration.
  • Space complexity: $O(1)$. We utilize constant space as we perform our running sum in-place.

Code

class Solution {
public:
    vector<int> runningSum(vector<int>& nums) {
        for (int i = 1; i < nums.size(); i++) {
            nums[i] += nums[i - 1];
        }
        return nums;
    }
};