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[0]…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[0] + A[1] + .... + 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[0] = nums[0];
        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
Please leave a comment below if you like this post or found some error, it will help me to improve my content.


Popular Posts from this Blog

LeetCode - Crawler Log Folder Solution - The Coding Shala

Richest Customer Wealth LeetCode Solution - The Coding Shala

First Unique Character in a String Java - The Coding Shala

Shell Script to find sum, product and average of given numbers - The Coding Shala

Add two numbers in Scala - The Coding Shala