LeetCode Problem 1480: Sum
SeriesLeetCodepart 1 of 10
- LeetCode Problem 1480: Sum
- LeetCode Problem 1672: Solving the Richest Customer Wealth Challenge
- Leetcode Question 412: Fizz Buzz - My Simple Solution
- LeetCode Question 1342: Number of Steps to Reduce a Number to Zero - My Simple Solution
- Solving LeetCode Problem 876: Middle of the Linked List
- LeetCode Question 383: Ransom Note Solution Breakdown
- LeetCode 977: Squares of a Sorted Array Solution
- LeetCode 1295: Find Numbers with Even Number of Digits
- LeetCode 485 - Finding Max Consecutive Ones
- Is Bitwise & Better than Arithmetic to Determine Even or Odd? Let’s Dive In!
On this page
The Problem
The challenge is pretty straightforward: you’re given an array of integers and you need to return a new array where each element is the running sum of the previous elements in the input array. The running sum at index (i) is defined as the sum of all elements from index 0 to index (i).
For example, if you have an input array:
[1, 2, 3, 4]
The output should be:
[1, 3, 6, 10]
Pretty simple, right? It’s like that moment when you realize that your snack stash has been dwindling down to nothing while you’re binge-watching your favorite series… suddenly you’ve eaten all the chips! Anyway, let’s code!
The Solution
Alright, let me break down the code I submitted for this problem. I crafted a neat little Java solution that does the job in one pass. Here it is:
class Solution {
public int[] runningSum(int[] nums) {
for (int i = 1; i < nums.length; i++) {
nums[i] = nums[i - 1] + nums[i];
}
return nums;
}
}
Complexity Analysis
Let’s talk performance real quick.
- Time Complexity: O(n), where n is the number of elements in the input array. You’re only looping through the array once!
- Space Complexity: O(1), because we’re modifying the input array in place. Just imagine how cluttered your workspace would be if you had to pull out new containers for everything… Not cool!
References: