LeetCode: Running Sum of 1D Array
Problem: Running Sum of 1D Array
class Solution:
def runningSum(self, nums: List[int]) -> List[int]:
if len(nums)<=1:
return nums
new_nums=[]
total=0
for num in nums:
total+=num
new_nums.append(total)
return new_nums
In runningSum :
If length of array is 1 or it’s empty then we simply return the list/array.
We create two important variables
new_nums, an array to store new items, each item being running sum of it’s previous items andtotalto do the cumulative sum here of the items that have been traversed. The main idea is to linearly traverse the original array, as we move and traverse the items, add the current item to the total. After every iteration, updated total is the new item to be appended and we append it to the new array created.We return the new array.