Loading collection data...
Collections are a way for you to organize kata so that you can create your own training routines. Every collection you create is public and automatically sharable with other warriors. After you have added a few kata to a collection you and others can train on the kata contained within the collection.
Get started now by creating a new collection.
[10,10] is the correct solution in that case
for input like [8,10,10,1] you'll get [10,10] instead of [8,10]
mutating array isn't
This can be solved in O(N) time & O(1) space.
I have basically no background in algorythm efficiency analysis so I don't focus on it ever so thank you for the explanation and suggestion; I would implement your solution using a
.reduce()
but it would equate to the same thing.I imagine that there are more difficult kata where efficiency of the solution plays a part in success or not and I actually avoid those as it isn't something that I have ever needed to take into account.
If you were to use
Array.sort()
, first create a new array by doingarray.slice(0)
, which will create a shallow copy of the input array. Then it can be sorted without mutating the input.However, just using a simple for loop allows you to complete this Kata in
O(n)
instead ofO(n log(n))
; Using sort means that for large arrays you're going to see a huge performance disadvantage versus just finding the max and second max using a for loop.Thanks for the comment. What solution suggestion do you have?
Any solution using sort isn't best practice, as it's possible to complete this Kata in one iteration over the input array instead of spending time to sort it.
(not to mention, this mutates the input array as well!)
someone as lazy as I was :)
Agreed. But the Kata does not state that this will be use extremely often and therefore should be performant. Honestly, I solved it quickly with this solution and moved on since it was so simple. Doing a slice would probably be better.
When I "Attempt" my solution all tests show as passed but I get an error "TypeError: Reduce of empty array with no initial value". I am using a sparse array and mapping over it to initialize the values.
Reading a what has been discussed I might be trying to be too tricky for what is being asked for. At the very least I think that the error should be better explained or more tests added to indicate what is wrong.
This comment is hidden because it contains spoiler information about the solution
Slightly more elegant than my brute force solution above.
Brute force.
I think some clarity would help with this problem. The word "combine" should somehow indicate sum because the original Project Euler problem means product.