TRT
Sign in
easyFoundationsLeetCode#running total

Running sum of an array

Return the running totals of an array, and see why recomputing each total from scratch is quadratic.

The Runtime Theory Team1 min read
Taught inCounting stepsBefore you can compare two algorithms, you need a way to measure them that doesn't depend on your laptop. Count the basic steps as a function of the input size.
Solve it

Solving happens on the judge — come back and mark it done

Sample cases

innums = [1, 2, 3, 4]

out[1, 3, 6, 10]

innums = [1, 1, 1, 1, 1]

out[1, 2, 3, 4, 5]

innums = [3, 1, 2, 10, 1]

out[3, 4, 6, 16, 17]

Given an array nums, return an array where element i is the sum of nums[0] through nums[i].

Before you code

Write the obvious version first: for each i, add up nums[0..i] with an inner loop. Count its additions for n elements. Then find a version where each answer costs one addition.

Hints

  1. The inner-loop version does 1 + 2 + … + n additions: n(n + 1)/2, which is O(n²).
  2. result[i] is result[i - 1] + nums[i]. The previous answer already contains everything except the new element.
  3. You can even overwrite nums in place, for O(1) extra space.

Production & complexity notes

When solving Running sum of an array on LeetCode (easy), always state your loop or recursion invariant before writing code. Verify how your chosen data structure behaves on degenerate inputs (single-element inputs, all-duplicate keys, strictly monotonic sequences, or maximum constraint sizes up to $10^5$ elements). In production interviews, pair your implementation with an explicit time and auxiliary space complexity proof, explain why alternative brute-force approaches violate the latency budget, and trace how cache locality and memory allocation overhead affect wall-clock throughput on real hardware. Review the step-by-step memory trace in Counting steps to reinforce the underlying pattern.

What it practices

Counting the steps of a nested loop and removing the repeated work, from Counting steps. The same running total is the basis of prefix sums, later in the track.

Not started

Sign in to save your learning progress.

Sign in to save