0

I'm working on a problem that requires the running sum within the array. Example, an array with the values [1,2,3,4] should return [1,3,6,10] and an array that holds [3,1,2,10,1] should output [3,4,6,16,17]. Right now I am stumped on what I am missing for my answer. I am thinking that I should handle this recursively in some way, but I am not sure how to begin with that. In any case, this is my current solution

var runningSum = function(nums) { let result = []; nums.forEach(function(num, idx) { if (idx === 0) { result.push(num); } else { result.push(num + nums[idx - 1]); } }); return result; } 

Leet code stated that this was a fairly easy problem, so I figured that I'm thinking way too hard on this and can solve it a lot easier. Let me know your thoughts. Thanks!

11
  • 1
    change num + nums[idx - 1] to num + result[idx - 1] so that you actually take into the account the sum of previous numbers and not just the last number Commented Aug 9, 2022 at 9:14
  • Or do this: jsfiddle.net/ugmpvL9n Commented Aug 9, 2022 at 9:16
  • Ah got it! Would it make sense to say that during the iteration, the nums array is represented by only one element? Commented Aug 9, 2022 at 9:18
  • You made it too complex: function runningSum(nums) { let temp = 0; return nums.map(el => (temp += el, temp)); } Example: wandbox.org/permlink/iOJnh6FR1cCBSu6z Commented Aug 9, 2022 at 9:22
  • @jabaa This works fine but writing to an external variable with .map() feels kind of icky to me ;) Commented Aug 9, 2022 at 9:25

1 Answer 1

1

A simpler (and more resource-friendly) way of approaching the problem would just be to use a for loop:

/** * @param {number[]} nums * @return {number[]} */ var runningSum = function(nums) { for (let i = 1; i < nums.length; i++) nums[i] += nums[i-1]; return nums; }; 
Sign up to request clarification or add additional context in comments.

3 Comments

Thank for you the response! When you say more resource-friendly, are you referring to space & time complexity? I am starting to learn more on this topic.
This modifes the input array. That's usually bad practice in JavaScript.
I was referring to performance tests done by others shown here. Other methods (such as for, for...of) perform relatively better than .forEach().

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.