Running Sum of 1d Array - Problem

Given an array nums, we need to compute the running sum (also known as cumulative sum or prefix sum) of the array.

The running sum at position i is defined as: runningSum[i] = sum(nums[0] + nums[1] + ... + nums[i])

Goal: Transform the input array so that each element becomes the sum of all elements from the start up to that position.

Example: If nums = [1, 2, 3, 4], then:
• Position 0: sum of [1] = 1
• Position 1: sum of [1, 2] = 3
• Position 2: sum of [1, 2, 3] = 6
• Position 3: sum of [1, 2, 3, 4] = 10
So the result is [1, 3, 6, 10]

Input & Output

example_1.py — Basic case
$ Input: nums = [1,2,3,4]
Output: [1,3,6,10]
💡 Note: Running sums: 1, 1+2=3, 1+2+3=6, 1+2+3+4=10
example_2.py — Single element
$ Input: nums = [5]
Output: [5]
💡 Note: Only one element, so running sum is just that element
example_3.py — With negative numbers
$ Input: nums = [1,-2,3,-4,5]
Output: [1,-1,2,-2,3]
💡 Note: Running sums: 1, 1+(-2)=-1, -1+3=2, 2+(-4)=-2, -2+5=3

Visualization

Tap to expand
Running Sum = Bank Account Balance TrackerTransaction 1:+$1Balance: $1Transaction 2:+$2Balance: $3($1 + $2)Transaction 3:+$3Balance: $6($3 + $3)Transaction 4:+$4Balance: $10($6 + $4)Array TransformationOriginal: [1, 2, 3, 4]Step 1: [1, 2, 3, 4] → nums[0] stays 1Step 2: [1, 3, 3, 4] → nums[1] = 2+1 = 3Step 3: [1, 3, 6, 4] → nums[2] = 3+3 = 6Step 4: [1, 3, 6, 10] → nums[3] = 4+6 = 10Final Result: [1, 3, 6, 10]Time: O(n), Space: O(1)✨ Each step uses the previous result!
Understanding the Visualization
1
Initial Balance
Start with first transaction: balance = $1
2
Transaction 2
Add $2 to existing balance: $1 + $2 = $3
3
Transaction 3
Add $3 to current balance: $3 + $3 = $6
4
Final Balance
Add $4 to current balance: $6 + $4 = $10
Key Takeaway
🎯 Key Insight: Instead of recalculating the entire sum for each position, maintain a running total by adding the current element to the previous sum. This transforms an O(n²) problem into an elegant O(n) solution!

Time & Space Complexity

Time Complexity
⏱️
O(n²)

For each of the n positions, we sum up to i elements, giving us 1+2+3+...+n = n(n+1)/2 operations

n
2n
Quadratic Growth
Space Complexity
O(1)

Only using constant extra space (excluding the output array which is required)

n
2n
Linear Space

Constraints

  • 1 ≤ nums.length ≤ 1000
  • -106 ≤ nums[i] ≤ 106
  • Follow-up: Can you solve this in-place with O(1) extra space?
Asked in
Amazon 25 Google 18 Microsoft 15 Meta 12
125.0K Views
High Frequency
~8 min Avg. Time
3.5K Likes
Ln 1, Col 1
Smart Actions
💡 Explanation
AI Ready
💡 Suggestion Tab to accept Esc to dismiss
// Output will appear here after running code
Code Editor Closed
Click the red button to reopen