Running Sum of 1d Array – Leetcode Solution

In this post, we are going to solve the 1480. Running Sum of 1d Array problem of Leetcode. This problem 1480. Running Sum of 1d Array is a Leetcode easy level problem. Let’s see the code, 1480. Running Sum of 1d Array – Leetcode Solution.

Problem

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

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

Example 3 :

Input: nums = [3,1,2,10,1]
Output: [3,4,6,16,17]

Constraints

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

Now, let’s see the code of 1480. Running Sum of 1d Array – Leetcode Solution.

Running Sum of 1d Array – Leetcode Solution

1480. Running Sum of 1d Array – Solution in 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] = nums[i]+ans[i-1];
        }
        return ans;
    }
}

1480. Running Sum of 1d Array – Solution in C++

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

1480. Running Sum of 1d Array– Solution in Python

 def runningSum(self, nums):
        i = 1
        while i<len(nums):
            nums[i]+=nums[i-1]
            i+=1
        return nums

Note: This problem 1480. Running Sum of 1d Array is generated by Leetcode but the solution is provided by CodingBroz. This tutorial is only for Educational and Learning purpose.

Leave a Comment

Your email address will not be published. Required fields are marked *