Easy 0 solved 0% acceptance

Running Sum

Replace each value with the total so far.

What you'll learn

  • Compute totals so far
  • Build a new list of results
  • Learn the prefix sum idea

Problem

Build a running sum: the value at position i is the sum of all numbers from position 0 through i.

Implement running_sum(numbers).

Input

numbers: The list of integers.

Output

Return the list of running totals.

Constraints

0 ≤ length ≤ 100,000; totals fit in a 64-bit integer

Examples

Example 1
Input:
numbers = [1, 2, 3, 4]

Expected output:
expected = [1, 3, 6, 10]
Input:
std::vector<long long> numbers = {1, 2, 3, 4};

Expected output:
std::vector<long long> expected = {1, 3, 6, 10};
Input:
long[] numbers = new long[] {1, 2, 3, 4};

Expected output:
long[] expected = new long[] {1, 3, 6, 10};

Explanation

Totals so far: 1, 1+2=3, 3+3=6, 6+4=10.

Example 2
Input:
numbers = [5, -5, 5]

Expected output:
expected = [5, 0, 5]
Input:
std::vector<long long> numbers = {5, -5, 5};

Expected output:
std::vector<long long> expected = {5, 0, 5};
Input:
long[] numbers = new long[] {5, -5, 5};

Expected output:
long[] expected = new long[] {5, 0, 5};

Explanation

Totals: 5, 0, 5.

How to approach it

Try on your own first, then open one hint at a time.

Hint 1

Each output element depends on the total of all earlier elements and itself.

Hint 2

Keep a cumulative total as you move through the list.

Hint 3

The first position should simply reflect the first input value.

Expected complexity

O(n) time, O(n) extra space

References

This challenge is adapted for CodeUtility. Follow the statement and constraints above.

Learn from others

Community solutions

No published solutions yet. Solve this challenge to share the first one.