Running Sum of 1D Array

01 Min
🔄
Lesson In Active Development In Progress

This lesson is currently being drafted and expanded with practical examples and diagrams. You can read the current draft as content is actively added.

Table of Contents 2 sections

Problem Overview

Problem Link

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.

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

Solution

Idea - Traverse the array and keep adding previous number to current index.

import java.util.*;
public class Main
{
	public static void main(String[] args) {
		int[] nums = new int[]{1,2,3,4};
		
		for(int i=1;i<nums.length;++i){
		    nums[i] = nums[i] + nums[i-1];
		}
		
		System.out.println(Arrays.toString(nums));
		
	}
}

Running Sum of 1D Array

Calculate the running sum by adding each element to the previous running sum. The input array is modified in-place, producing the prefix sum at every index.

Initialize Array

length: 4

Start with the input array [1, 2, 3, 4]. We will calculate the running sum in-place.

$ int[] nums = new int[]{1,2,3,4};
1
[0]
2
[1]
3
[2]
4
[3]
Step 1 of 9
Speed