BackeasyArraysHCL

Cumulative Array Sum Solution

Problem Statement

Given an array of integers 'scores', compute and return the cumulative sum after every index.

Example 1
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].

Example 2
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
Live Compiler1 Free Run Available
Loading Editor...
Test Cases & Output
Click "Run" to test your 1 free compile trial!

🚀 Practice this problem

Run code, get AI hints & track streak

Sign Up Free

Cumulative Array Sum — Problem Statement & Solution Guide

ArraysEasyPrefix Sum
TimeO(n)
|
SpaceO(n)

Problem Description

Given an array of integers 'scores', compute and return the cumulative sum after every index.

Examples

Example 1

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].

Example 2

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

JavaScript Solution
Time: O(n)
function cumulativeSum(arr) { let sum = 0; return arr.map(num => sum += num); }

Asked in Top Tech Interviews

HCL

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.