Given an array nums, define its running sum as runningSum[i] = sum(nums[0]…nums[i]). Return the running sum of nums.
nums = [1,2,3,4][1,3,6,10]nums[i] += nums[i-1]At each step, nums[i-1] already holds the sum of elements 0..i-1. Adding it to nums[i] extends the running total by one element. This builds the prefix sum left to right in a single pass with no extra array needed.
The brute force re-adds everything from the start for each position. That's O(n²), and it repeats the same additions again and again.
Each running sum is the previous running sum, plus the current number. So walk left to right, and add the previous value into the current one, in place.
Prefix sum at i equals prefix sum at i −1, plus the value at i. This prefix sum idea is the base of many harder array problems.
Run the animation above on your own input, or watch the 1:13 video explanation of Running Sum of 1D Array with a dry run and Java code.