Grokking the Engineering Manager Coding Interview

0% completed

Running Sum of 1d Array (easy)

Problem Statement

Examples

Try it yourself

Problem Statement

Given a one-dimensional array of integers, create a new array that represents the running sum of the original array.

The running sum at position i in the new array is calculated as the sum of all the numbers in the original array from the 0th index up to the i-th index (inclusive). Formally, the resulting array should be computed as follows: result[i] = sum(nums[0] + nums[1] + ... + nums[i]) for each i from 0 to the length of the array minus one.

Examples

Example 1

  • Input: [2, 3, 5, 1, 6]
  • Expected Output: [2, 5, 10, 11, 17]
  • Justification:
    • For i=0: 2
    • For i=1: 2 + 3 = 5
    • For i=2: 2 + 3 + 5 = 10
    • For i=3: 2 + 3 + 5 + 1 = 11
    • For i=4: 2 + 3 + 5 + 1 + 6 = 17

Example 2

  • Input: [1, 1, 1, 1, 1]
  • Expected Output: [1, 2, 3, 4, 5]
  • Justification: Each element is simply the sum of all preceding elements plus the current element.

Example 3

  • Input: [-1, 2, -3, 4, -5]
  • Expected Output: [-1, 1, -2, 2, -3]
  • Justification: Negative numbers are also summed up in the same manner as positive ones.

Constraints:

  • 1 <= nums.length <= 1000
  • -10^6 <= nums[i] <= 10^6

Try it yourself

Try solving this question here:

Python3
Python3

. . . .

Please check the next lesson for a complete solution.

Mark as Completed
Aravind Badiger

Aravind Badiger

· 2 years ago

Whether we consider a returning result variable or replace elements in the original array the space complexity is O(1)

Show 1 reply
E

ethanedge

· 19 days ago

The solution states:

  • Check for Edge Cases:
    • If the input array is null or has no elements, return an empty array since there's nothing to process.

However, the question states:

Constraints:

  • 1 <= nums.length <= 1000

Which could be confusing to some as it's contradictory.

Show 1 reply
Rafael Scarduelli

Rafael Scarduelli

· 2 years ago

This happens on line 4 when trying to get nums[0].

Show 1 reply
rcreddyn

rcreddyn

· 7 days ago

Is the check for empty array or null necessary as contraints state the minimum size of the array is 1?

On This Page

Problem Statement

Examples

Try it yourself