↓Skip to main content
  1. LeetCode/

LeetCode 1480: Running Sum of 1d Array

·1 min· ·
LeetCode Easy Array Prefix-Sum
Wei Yi Chung
Author
Wei Yi Chung
Working at the contributing of open source, distributed systems, and data engineering.
Table of Contents

Meta Data
#

Difficulty: easy First Attempt: 2022-11-23

  • Submissions: Accepted (first try)

Approach
#

The prefix sum itself (Prefix Sum): res[i] = res[i - 1] + nums[i]. In Python, itertools.accumulate does it directly.

My Solution
#

class Solution:
    def runningSum(self, nums: List[int]) -> List[int]:
        for i in range(1, len(nums)):
            nums[i] += nums[i - 1]
        return nums

Complexity
#

Time O(n), space O(1) in place.

Mistakes to Avoid
#

  • Start at index 1; element 0 stays as is.

Interview Explanation
#

Adding the previous total to each element gives the prefix sums, done in place in O(n).

Related

LeetCode 1413: Minimum Value to Get Positive Step by Step Sum
·1 min
LeetCode Easy Array Prefix-Sum
LeetCode 1413 note: the start value plus every prefix sum must be at least 1, so it is max(1, 1 - minimum prefix sum)
LeetCode 1732: Find the Highest Altitude
·1 min
LeetCode Easy Array Prefix-Sum
LeetCode 1732 note: the altitudes are prefix sums of gain starting from 0; take the maximum
LeetCode 1991: Find the Middle Index in Array
·1 min
LeetCode Easy Array Prefix-Sum
LeetCode 1991 note: compute the total, maintain the left sum while scanning, and get the right sum as total - left - nums[i]
LeetCode 1337: The K Weakest Rows in a Matrix
·1 min
LeetCode Easy Array Binary-Search Sorting Heap-Priority-Queue
LeetCode 1337 note: soldiers come first in each row, so binary search the first 0 for the count; sort by (count, row index) and take k
LeetCode 1160: Find Words That Can Be Formed by Characters
·1 min
LeetCode Easy Array Hash-Table String Counting
LeetCode 1160 note: a word is formable when none of its character counts exceeds chars’; sum the lengths of such words
LeetCode 1051: Height Checker
·1 min
LeetCode Easy Array Sorting Counting-Sort Bubble-Sort
LeetCode 1051 note: sort and count the positions that differ from the original