Community Problem

Running Sum of 1d Array

Difficulty: Easy

Build the prefix-sum array in place: each output index holds the cumulative sum of nums up to that index.

Running Sum of 1d Array

Build the prefix-sum array in place: each output index holds the cumulative sum of nums up to that index.

EASY
Free
arrays
prefix-sum
fundamentals
leoeriksson

By @leoeriksson

December 21, 2025

·

Updated May 20, 2026

645 views

2

Rate

I keep this one on my warmup list when an intern asks how prefix-sum actually works in code, because the entire pattern fits in a three-line loop and the answer doubles as the data structure half the harder array problems need. The official practice catalog covers Subarray Sum Equals K and Range Sum Query, but it skipped the gentle, no-tricks introduction that every prefix-sum chain ultimately reduces to.

Running Sum of 1d Array

Given an integer array nums, return an array result of the same length where result[i] = nums[0] + nums[1] + ... + nums[i]. The returned array is the running sum (also called the prefix-sum) of nums.

Examples

Example 1:

  • Input: nums = [1, 2, 3, 4]
  • Output: [1, 3, 6, 10]
  • Explanation: Running sum is [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: Each step adds another 1 to the running total.

Example 3:

  • Input: nums = [3, 1, 2, 10, 1]
  • Output: [3, 4, 6, 16, 17]
  • Explanation: Running sum after each index in nums.

Example 4:

  • Input: nums = [-1, 2, -3, 4]
  • Output: [-1, 1, -2, 2]
  • Explanation: Running sums can decrease when negative values appear.

Constraints

  • 1 <= nums.length <= 1000
  • -10^6 <= nums[i] <= 10^6

Follow-up

Can you do this in O(1) extra space, mutating nums in place rather than allocating a new array?

Solution

Hints

0/4
Hint 1
Hint 2
Hint 3
Hint 4
All Problems