Member-only story
Leetcode 5453. Running Sum of 1d Array
2 min readJun 14, 2020
In this Leetcode problem, we are asked to return the sum
array given an nums
array where sum[i] = sum(nums[0],…, nums[i])
Solution
A few ideas for this problem:
- We will use the input array and modify it, and return it as the solution. That way, we don’t have to create a new array.
- We will build a loop such that after each step
i
,nums[i]
contains the expected value forsum[i]
- Given that
nums[i]
contains the sum value, andnums[i+1]
wasn’t modified, we assignnums[i+1] = nums[i+1] + nums[i]
at the stepi+1
.
class Solution {
public int[] runningSum(int[] nums) {
for (int i = 1; i < nums.length; i++) {
nums[i] += nums[i - 1];
}
return nums;
}
}
This solution runs in O(n) time, with n the size of the input array, and beats 100% of the Java solutions.
Happy coding :)
What’s next:
- Checkout the solution for another problem: Rearrange words in a sentence
- Contact me: poitevinpm@gmail.com
- Looking to interview for a software engineer position? Contact me :)