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
- The inner-loop version does 1 + 2 + … + n additions: n(n + 1)/2, which is O(n²).
result[i]isresult[i - 1] + nums[i]. The previous answer already contains everything except the new element.- You can even overwrite
numsin 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.