Sums of Parts challenge

I am solving Sums of Parts challenge by codewars platform. I think that I solved the challenge but I still need to deal with arrays have thousands of elements. My code:

function partsSums(ls) {
    let length = ls.length;
    let newArr = [ls.reduce((acc, cur) => acc + cur, 0)];
    for (let i = 0; i < length; i++) {
        ls.splice(0, 1);
        newArr.push(ls.reduce((acc, cur) => acc + cur, 0))
    }
    return newArr;
}

The link of the challenge: https://www.codewars.com/kata/5ce399e0047a45001c853c2b/train/javascript

Hi @abdulrahmanmhdanas

You need to format your code.

What did you mean by formatting my code?

@SamA74 has done it for you this time, but when you post code on the forums, you need to format it so that it will display correctly.

You can highlight your code, then use the </> button in the editor window, which will format it.

Or you can place three backticks ``` (top left key on US/UK keyboards) on a line before your code, and three on a line after your code. I find this approach easier, but unfortunately some European and other keyboards don’t have that character.

The trick here is not to treat the array from top to bottom, but from bottom to top. That is, the sum of step n-1 is equal to the sum at step n + the element that was removed at step n.

To make it visual, I’ve reversed the order of the array as shown in the instructions:

ls = []               // sum = 0  = 0
ls = [10]             // sum = 10 = 0 + 10
ls = [6, 10]          // sum = 16 = 0 + 10 + 6
ls = [3, 6, 10]       // sum = 19 = 0 + 10 + 6 + 3
ls = [1, 3, 6, 10]    // sum = 20 = 0 + 10 + 6 + 3 + 1
ls = [0, 1, 3, 6, 10] // sum = 20 = 0 + 10 + 6 + 3 + 1 + 0
// NOTE:                            ^   ^^   ^   ^   ^

See the pattern emerging here?

1 Like

@rpkamp my head hurts :smiley:

I have to confess I know a solution now — I felt very stupid when I saw it. Without giving the game away (too much) it involved subtraction. (Possibly what you are pointing out?)

Will look at your post again tomorrow, when I can get my head on straight. Thank you.

2 Likes

Right, yes, that works. I had a solution using addition, and even though it was way faster than the original it still timed out. I reworked my solution and it doesn’t time out anymore :clap:

2 Likes

This topic was automatically closed 91 days after the last reply. New replies are no longer allowed.