#1480

Running Sum of 1d Array

Easy Single pass

  1. Read
  2. Understand
  3. Hints
  4. Approach
  5. Solution
  6. Solved

?The problem

Given an array, return a new array where each position holds the total of all elements from index 0 up to that position.

This is a short summary in our own words. Read the full statement and examples on LeetCode: open problem ↗

◎Understanding

Really asking: for each position, what is the total of everything up to here? The answer for one position is just the answer for the position before it plus one more number.

Why this works: we reuse the total we already have instead of adding everything again. That turns O(n²) into O(n).

Example: nums = [1, 2, 3, 4]

i=0: total = 1                → [1, 2, 3, 4]i=1: total = 1 + 2 = 3        → [1, 3, 3, 4]i=2: total = 3 + 3 = 6        → [1, 3, 6, 4]i=3: total = 6 + 4 = 10       → [1, 3, 6, 10]

✦Hints open one at a time

↗Approach

</>Solution (Java)

!Common mistake

Starting the loop at i = 0 and reading nums[-1]. Start at i = 1.