#1480
Running Sum of 1d Array
EasyArrayPrefix SumPrefix SumArray
Approaches
Brute ForceOptimal
Complexity Comparison
| Brute Force | Optimal Solution★ | |
|---|---|---|
| Time | O(n²) | O(n) |
| Space | O(1) | O(n) |
💡
Intuition
Time O(n)Space O(n)
The optimal solution leverages the fact that each running sum can be derived from the previous running sum, which allows us to compute the result in a single pass through the array.
⚙️
Algorithm
5 steps- 1Step 1: Initialize a variable 'currentSum' to 0.
- 2Step 2: Create an array 'runningSum' of the same length as 'nums'.
- 3Step 3: Iterate through 'nums', adding each element to 'currentSum'.
- 4Step 4: Store 'currentSum' in the corresponding index of 'runningSum'.
- 5Step 5: Return 'runningSum' after processing all elements.
solution.py9 lines
1# Full working Python code
2
3def runningSum(nums):
4 runningSum = [0] * len(nums)
5 currentSum = 0
6 for i in range(len(nums)):
7 currentSum += nums[i]
8 runningSum[i] = currentSum
9 return runningSumℹ
Complexity note: The time complexity is O(n) because we only loop through the array once. The space complexity is O(n) due to the output array 'runningSum' that we create.
- 1The running sum can be built incrementally using the previous sum.
- 2Understanding the relationship between current and previous elements is key to optimizing the solution.
Solutions and explanations are original Tejav content. Problem titles © LeetCode — use the LeetCode button above for the full problem statement.