Running Sum of 1d Array - Problem

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 & Output

Example 1 — Basic Case
$ Input: nums = [1,2,3,4]
Output: [1,3,6,10]
💡 Note: Running sums: [1, 1+2, 1+2+3, 1+2+3+4] = [1,3,6,10]
Example 2 — Single Element
$ Input: nums = [1]
Output: [1]
💡 Note: Only one element, so running sum is just [1]
Example 3 — With Negative Numbers
$ Input: nums = [1,1,1,1,1]
Output: [1,2,3,4,5]
💡 Note: Running sums of identical elements: [1, 1+1, 1+1+1, 1+1+1+1, 1+1+1+1+1]

Constraints

  • 1 ≤ nums.length ≤ 1000
  • -106 ≤ nums[i] ≤ 106

Visualization

Tap to expand
Running Sum of 1d Array INPUT Original Array: nums 1 i=0 2 i=1 3 i=2 4 i=3 Input Values nums = [1, 2, 3, 4] Goal: Compute running sum at each index runningSum[i] = sum(0..i) ALGORITHM STEPS (In-Place Modification) 1 Start at i=1 Skip index 0 (already OK) 2 Add Previous nums[i] += nums[i-1] 3 Move Forward Increment i, repeat 4 Return Result Array now has sums Iterations i=1: [1, 1+2, 3, 4] --> [1,3,3,4] i=2: [1, 3, 3+3, 4] --> [1,3,6,4] i=3: [1, 3, 6, 6+4] --> [1,3,6,10] FINAL RESULT Running Sum Array 1 sum=1 3 sum=3 6 sum=6 10 sum=10 Output [1, 3, 6, 10] Verification 1 = 1 OK 1+2 = 3 OK 1+2+3 = 6 OK 1+2+3+4 = 10 OK Key Insight: In-place modification uses O(1) extra space. Each element accumulates the sum of all previous elements. By the time we reach index i, nums[i-1] already contains sum(0..i-1), so we just add nums[i] to it. TutorialsPoint - Running Sum of 1d Array | In-Place Modification Approach Time: O(n) | Space: O(1)
Asked in
Amazon 15 Microsoft 8 Google 6
85.0K Views
High Frequency
~10 min Avg. Time
4.2K 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