Cumulative Array Sum — Problem Statement & Solution Guide
Problem Description
Given an array of integers 'scores', compute and return the cumulative sum after every index.
Examples
Input
[1, -1, 2, -2]
Output
[1, 0, 2, 0]
Explanation: The core concept here is the Running Sum (also known as Prefix Sum). The output array accumulates the sum of elements from index 0 up to the current index. Each position i in the output is computed as Output[i] = Output[i-1] + Input[i]. For index 0, Output[0] is simply Input[0].
Input
[-1, -2, 3, 4]
Output
[-1, -3, 0, 4]
Explanation: Each element at index i is the cumulative sum of elements from the start of the array up to index i. By keeping a running total as we iterate through the array, we can compute the sum for each position in a single pass.
Constraints
- 1 <= n <= 1000
- -10^6 <= arr[i] <= 10^6
Optimal Approach & Strategy
Start from index 1, add the value of previous element to current element. Time O(N), Space O(1).
Brute Force Approach
For each index i, run a loop from 0 to i to sum elements. Time O(N^2).
Verified Code Solutions
function cumulativeSum(arr) { let sum = 0; return arr.map(num => sum += num); }class Solution {
public int[] cumulativeSum(int[] scores) {
int[] cumulative = new int[scores.length + 1];
cumulative[0] = 0;
for (int i = 1; i <= scores.length; i++) {
cumulative[i] = cumulative[i - 1] + scores[i - 1];
}
return java.util.Arrays.copyOfRange(cumulative, 1, cumulative.length);
}
}def cumulative_sum(scores):
cumulative = [0]
for score in scores:
cumulative.append(cumulative[-1] + score)
return cumulative[1:]
function cumulativeSum(arr) { let sum = 0; return arr.map(num => sum += num); }Asked in Top Tech Interviews
Solve in Interative Editor
Ready to test your code? Open our built-in compiler, run custom test suites, and see detailed complexity analysis reports instantly.