Leetcode 1480. Running Sum of 1d Array
The problem asks for the running sum of a 1D array. The running sum of a given array is defined as a new array where the i-th
element is the sum of the first i+1
elements of the original array.
For example, if the input is nums = [1, 2, 3, 4]
, the running sum would be [1, 3, 6, 10]
.
Assuming standard constraints:
[-10^6, 10^6]
.1
and 10^4
.public class Solution {
public int[] runningSum(int[] nums) {
// Handling edge cases with input constraints
if (nums == null || nums.length == 0) {
return new int[0];
}
// Create an array to store the running sum
int[] runningSumArray = new int[nums.length];
// Initialize the first element of runningSumArray
runningSumArray[0] = nums[0];
// Loop through the array starting from the second element
for (int i = 1; i < nums.length; i++) {
// Calculate running sum by adding the current element to the previous running sum
runningSumArray[i] = runningSumArray[i - 1] + nums[i];
}
return runningSumArray;
}
public static void main(String[] args) {
Solution sol = new Solution();
int[] nums = {1, 2, 3, 4};
int[] result = sol.runningSum(nums);
// Printing the result should give [1, 3, 6, 10]
for (int num : result) {
System.out.print(num + " ");
}
}
}
The algorithm has a time complexity of (O(n)), where (n) is the number of elements in the input array. This is because we iterate through the array once to calculate the running sum.
The space complexity is (O(n)) due to the additional array used to store the running sums.
Got blindsided by a question you didn’t expect?
Spend too much time studying?
Or simply don’t have the time to go over all 3000 questions?