LeetCode 1480: Running Sum of 1d Array
Problem Description
Explanation
To calculate the running sum of an array, we can iterate through the array and keep adding the current element to the running sum. We can update the current element with the running sum at each index. This way, each element will represent the running sum up to that index.
-
Algorithm:
- Initialize a running sum variable to 0.
- Iterate through the array.
- For each element, add it to the running sum and update the element with the running sum.
- Return the modified array.
-
Time Complexity: O(n) where n is the number of elements in the array.
-
Space Complexity: O(1) since we are modifying the input array in place.
Solutions
class Solution {
public int[] runningSum(int[] nums) {
int sum = 0;
for (int i = 0; i < nums.length; i++) {
sum += nums[i];
nums[i] = sum;
}
return nums;
}
}
Loading editor...