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: Step-by-step: For input [1, -1, 2, -2], we start with 0. At index 0, we add 1 to get 1. At index 1, we add -1 to get 0. At index 2, we add 2 to get 2. At index 3, we add -2 to get 0.
Input
[-1, -2, 3, 4]
Output
[-1, -3, 0, 4]
Explanation: Step-by-step: For input [-1, -2, 3, 4], we start with 0. At index 0, we add -1 to get -1. At index 1, we add -2 to get -3. At index 2, we add 3 to get 0. At index 3, we add 4 to get 4.
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.