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.
I used let keyword here it failed some tests, I had to change, check mine.
removing from the begining of the array is another expensive solution
Your solution is
O(n^2)
. The recursion is onen
and theindexOf
is another.I put in a O(n) version, with unnecessary recursion, just 'cause.
I agree with @alemontree that this should NOT be voted as best practice. Granted my solution is nearly identical. However I am aware that this solution is suboptimal. I wish I could understand how to write this with at least linear efficiency. I will learn in time! It's good to make people aware of this so they can optimize their code!
That was my understanding as well, as it was noted in the description that some arrays are quite large. I'm surprised this was voted as "best practices" so many times.
Well, blame the author for not implementating performance tests?
By the way, do you know that if you know your array is almost sorted, using insertion sort gives a performance of O(kn) compared of quicksort's O(n log(n)). You can't talk about "optimal algorithm" without knowing what data you're actually handling ;-) So my point is still perfectly valid.
Oh, and also, in case you don't know already, most people in CW are noobs, so don't expect too much.
Oh, yes. Bubble sort is cool, because it might finish in one go contrary to other O(N∙logN) solutions. Bullshit.
Most tasks on codewars are just tolerable to unoptimal solutions, so many people don't even suspect this is not very good one.
Actually, it's enough to have 10 such people to have 10 upvotes for this solution as "best practices".
It's the best one out of all
O(n^2)
solutions. And in case the gap is always big, this would be faster than anO(n)
solution.Depending on the characteristics of the data this would actually be much faster than always iterating through the array.
Why do people upvote this as "best practices"? This is a O(n^2) solution for a problem that can be solved in linear time.
Same as i wrote two month ago some lines below...
While this deinitely works and looks neat, it is not a "best practices" solution. Sorting is an expensive operation is completely unnecessary in this case.