Code Logo

Running Sum of 1D Array

Published at05 Jan 2026
1D Array Easy 17 views
Like10

This problem feels like a little puzzle you can solve one step at a time. In Running Sum of 1D Array, you are trying to work toward the right list by following one clear idea.

This one is about building the best total or working out a final amount. You may need to choose which values should be included and which ones should be skipped. Sometimes the biggest number is not the smartest first choice if it hurts the rest of the plan. The goal is to finish with the best overall total, not just one good moment.

For example, if the input is nums = [1,2,3,4], the answer is [1,3,6,10]. Example with input: nums = [1,2,3,4] Another example is nums = [3,1,2,10,1], which gives [3,4,6,16,17]. Example with input: nums = [3,1,2,10,1]This is a friendly practice problem, but it still rewards careful reading. The key is thinking about the whole plan, not only one choice at a time.

Example Input & Output

Example 1
Input
nums = [1,2,3,4]
Output
[1,3,6,10]
Explanation

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

Example 2
Input
nums = [3,1,2,10,1]
Output
[3,4,6,16,17]
Explanation

Example with input: nums = [3,1,2,10,1]

Example 3
Input
nums = [1,1,1,1,1]
Output
[1,2,3,4,5]
Explanation

Example with input: nums = [1,1,1,1,1]

Algorithm Flow

Recommendation Algorithm Flow for Running Sum of 1D Array

Solution Approach

Compute the running sum of an array where each element at index i is the sum of the original elements from index 0 to i. Initialize result[0] = nums[0]. For each subsequent index, result[i] = result[i-1] + nums[i]. Return the running sum array.

function runningSum(nums) {
  var result = [nums[0]];
  for (var i = 1; i < nums.length; i++) {
    result.push(result[i - 1] + nums[i]);
  }
  return result;
}

Each element accumulates the previous total plus the current value. This single-pass approach computes the cumulative sum in O(n) time.

Time complexity is O(n), space complexity is O(n).

Best Answers

java
class Solution {
    public int[] running_sum(int[] nums) {
        int[] result = new int[nums.length];
        int total = 0;
        for (int i = 0; i < nums.length; i++) {
            total += nums[i];
            result[i] = total;
        }
        return result;
    }
}