Running Sum of 1d Array

In this problem, we will receive an array of numbers, and we must return an array where every number is the sum of it previously numbers.

Input: nums = [1,2,3,4]
Output: [1,3,6,10]
Explanation: Running sum is obtained as follows: [1, 1+2, 1+2+3, 1+2+3+4].

To approach this problem, we will use an auxiliar variable to store the sum of every passed number in the loop.

var sum = 0
  1. We will loop over the given array, at same time we will make a new array using map function
  2. Updating the auxiliar variable with the sum of its value and every new element
  3. Getting the auxiliar value
class Solution {
    func runningSum(_ nums: [Int]) -> [Int] {
        var sum = 0         // Auxiliar variable
        return {   // 1. Map function. Iterate over array and apply transformer for every element
            sum += $0       // 2. Updating auxiliar variable
            return sum      // 3. Get sum value to the looped element
Time complexity: O(n)
Due we only loop every element of the given array

Space complexity: O(1)
Due we are creating a variable to update the sum value