Menu
CoddyTech

Running Sum of an Array

BeginnerPrefix sumpython iconjava iconcpp iconc iconjs icon+10

You get an array of integers nums. Return a new array of the same length whose element at index i is nums[0] + nums[1] + ... + nums[i], the running total after reading the first i+1 numbers from the left.

Function

runningSum(nums: integer-array) → integer-array
numsinteger-array
the numbers to add up from left to right
Returnsinteger-array
the running totals, one for each element of nums

Constraints

  • 1 ≤ nums.length ≤ 5000
  • -104 ≤ nums[i] ≤ 104
  • Every running total fits in a 32-bit signed integer.

Examples

Input
nums = [3, 1, 4, 1, 5]
Output
[3, 4, 8, 9, 14]
Explanation
Keep adding: 3, then 3 + 1 = 4, 4 + 4 = 8, 8 + 1 = 9 and 9 + 5 = 14. Each total goes to the index of the number added last.

lock icon+13 hidden tests on Submit

challenge icon

Follow-up

Can you build the same thing for a grid, where each cell holds the total of the rectangle from the top-left corner to that cell?

Reset code
def runningSum(nums):
    # Write code here
Test cases

Case 1

Case 2

Case 3

Input

nums = [3, 1, 4, 1, 5]

Expected

[3, 4, 8, 9, 14]