### LeetCode - Running Sum of 1d Array Solution - The Coding Shala

Home >> LeetCode >> running sum of 1d array

In this post, we will learn how to solve LeetCode's Running Sum of 1d Array problem and its solution in Java.

## Running Sum of 1d Array

Given an array nums. We define a running sum of an array as runningSum[i] = sum(nums…nums[i]). Return the running sum of nums.

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

## Running Sum of 1d Array Java Solution

Approach 1:
Creating a new Array. consider given array is A and we will create a new Array B then:
B[i] = A + A + .... + A[i] or or we can write as B[i] = A[i] + B[i-1].

Time: O(n).
Space: O(n).

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

Approach 2:
We can modify the same array.

Time: O(n).
Space: O(1).

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

Other Posts You May Like