Running Sum of 1d Array

ID: 1480; easy

Solution 1 (Java)

class Solution {
    public int[] runningSum(int[] nums) {
        int[] ans = new int[nums.length];
        ans[0] = nums[0];
        for (int i = 1; i < nums.length; i++) {
            ans[i] = ans[i - 1] + nums[i];
        }
        return ans;
    }
}

A little teaser for DP.

Solution 2 (Java)

class Solution {
    public int[] runningSum(int[] nums) {
        for (int i = 1; i < nums.length; i++) {
            nums[i] += nums[i - 1]; 
        }
        return nums;
    }
}

The separate array is not actually needed. We can do the adding process in place. The complexities stay the same though.

  • Time complexity: O(n)

  • Space complexity: O(1)

Last updated