
Problem
Solution
Submissions
Running Sum of 1D Array
Certification: Basic Level
Accuracy: 0%
Submissions: 1
Points: 5
Write a Java program to compute the running sum of a 1D array. A running sum (also known as a cumulative sum) is defined as the sum of all elements up to a given index in an array, inclusive. For example, given an array nums = [1, 2, 3, 4]
, the running sum is [1, 1+2, 1+2+3, 1+2+3+4] = [1, 3, 6, 10]
.
Example 1
- Input: nums = [1, 2, 3, 4]
- Output: [1, 3, 6, 10]
- Explanation:
- Step 1: Initialize a new array to store the running sum values.
- Step 2: The first element of the running sum array is the same as the first element of the input: 1.
- Step 3: For the second element, add the second element of the input to the previous running sum: 1 + 2 = 3.
- Step 4: For the third element, add the third element of the input to the previous running sum: 3 + 3 = 6.
- Step 5: For the fourth element, add the fourth element of the input to the previous running sum: 6 + 4 = 10.
- Step 6: Return the running sum array [1, 3, 6, 10].
Example 2
- Input: nums = [3, 1, 2, 10, 1]
- Output: [3, 4, 6, 16, 17]
- Explanation:
- Step 1: Initialize a new array to store the running sum values.
- Step 2: The first element of the running sum array is the same as the first element of the input: 3.
- Step 3: For the second element, add the second element of the input to the previous running sum: 3 + 1 = 4.
- Step 4: For the third element, add the third element of the input to the previous running sum: 4 + 2 = 6.
- Step 5: For the fourth element, add the fourth element of the input to the previous running sum: 6 + 10 = 16.
- Step 6: For the fifth element, add the fifth element of the input to the previous running sum: 16 + 1 = 17.
- Step 7: Return the running sum array [3, 4, 6, 16, 17].
Constraints
- 1 ≤ nums.length ≤ 1000
- -10^6 ≤ nums[i] ≤ 10^6
- Time Complexity: O(n)
- Space Complexity: O(1) excluding the output array
Editorial
My Submissions
All Solutions
Lang | Status | Date | Code |
---|---|---|---|
You do not have any submissions for this problem. |
User | Lang | Status | Date | Code |
---|---|---|---|---|
No submissions found. |
Solution Hints
- Create an output array of the same size as the input array
- The first element of the output array will be the same as the first element of the input
- For each subsequent element at index i, add the value of the previous running sum (at index i-1) to the current element value
- Iterate through the array once to compute the running sum
- Return the running sum array