Problem 259569 · easy · Level 02 Linear Data Structures

Running Totals

arrays · prefix sums · accumulation

Given a list of integers nums, return a new list out of the same length where out[i] is the sum of nums[0] through nums[i] inclusive.

Examples

Input:  nums = [2, 7, 1, 8]
Output: [2, 9, 10, 18]

Input:  nums = [5, -5, 5]
Output: [5, 0, 5]

Constraints

  • 0 <= len(nums) <= 10**5
  • -10**4 <= nums[i] <= 10**4
  • Return a new list; do not modify nums. One test calls nums_after(nums), which runs your running_totals, appends an item to the list you returned and then returns nums itself, so it must come back unchanged.
  • Target: O(n) time; recomputing sum(nums[:i+1]) for each i is too slow.

Goals

  • Carry an accumulator through a single pass
  • Build a prefix-sum list of the same length as the input
  • Handle negatives and the empty list
Starting Python…