
Kotlin, Java
Leetcode — Running Sum of a 1D array
December 28, 2024
Leetcode — Running Sum of a 1D array
The Leetcode problem Running Sum of 1D array is tagged as an easy question. Running Sum of 1d Array - LeetCode
The problem statement is as follows:
Given an array *nums*. We define a running sum of an array as runningSum[i] = sum(*nums*[0]...*nums*[i]).
Return the running sum of *nums*
Examples
Constraints
Brainstorm
This problem is pretty straightforward. One way to solve this is to have a variable that adds the current value to it as we loop through the array. We will then add the sum’s current value to the current number in the loop.
Below are examples of this solution in Java and Kotlin.
Java:
// https://leetcode.com/problems/running-sum-of-1d-array/
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;
}
}
Kotlin:
// https://leetcode.com/problems/running-sum-of-1d-array/
class Solution {
fun runningSum(nums: IntArray): IntArray {
var sum = 0
nums.forEachIndexed{ i, num ->
sum += num
nums[i] = sum
}
return nums
}
}