AlgoInsight

DSA problem

Running Sum of 1d Array

EasyPrefix SumPattern: Prefix Sumtop600AmazonGoogle

Given an array nums, you compute a running sum of the array. The running sum is defined as runningSum[i] = sum(nums[0]…nums[i]).

Return the running sum of nums.

This is the canonical introduction to the prefix-sum technique: each output position holds the cumulative total of all elements up to and including that index. It can be done in a single pass and, by writing results back into the input, in constant extra space.

Examples

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]
Explanation: Each element adds itself to the cumulative total of all earlier elements.

Constraints

3 hints and a full solution walkthrough with step-by-step visualizations are available in the practice editor.

prefix-sumarray

Browse all DSA problems