Running Sum of 1d Array | Leetcode 1480 | Data Structure Interview Question
Вставка
- Опубліковано 5 лют 2025
- The Running Sum of 1D Array is a common problem on LeetCode. The task is to compute the cumulative sum of an array, where the value at each index is the sum of all elements up to that index in the original array.
Here’s an example of how to solve it:
Problem Statement:
Given an array nums, return an array result such that result[i] is the sum of nums[0] to nums[i].
Python Solution:
python
Copy code
class Solution:
def runningSum(self, nums: List[int]) - List[int]:
for i in range(1, len(nums)):
nums[i] += nums[i - 1]
return nums
Explanation:
Input:
nums = [1, 2, 3, 4]
Process:
At index 1, nums[1] += nums[0] → nums[1] = 3
At index 2, nums[2] += nums[1] → nums[2] = 6
At index 3, nums[3] += nums[2] → nums[3] = 10
Output:
nums = [1, 3, 6, 10]
Complexity:
Time Complexity:
𝑂
(
𝑛
)
O(n), where
𝑛
n is the length of the array.
Space Complexity:
𝑂
(
1
)
O(1), as the computation is done in-place.
This is an efficient in-place solution suitable for competitive programming and LeetCode submissions. Let me know if you’d like to discuss edge cases or variations!@TechWithMachines #algorithm #datastructures #leetcode #arrays #runningsumof1darray - Наука та технологія