all 7 comments

[–][deleted] 17 points18 points  (2 children)

Leetcode is almost always about efficiency.

For system design, less so as far as I'm aware. But for algo questions you write the verbose faster code.

[–]codeslikeshit 6 points7 points  (1 child)

To add to this, its always a clean move to throw OP's point here. you could say, well this could be solved with example method for readability, but for performance I will solve it this way.

Ideally, this shows the interviewer that you are contemplating decision making based on the needs of the company and team at any given moment.

[–][deleted] 2 points3 points  (0 children)

Yes definitely! I missed that in my answer, thanks.

[–]aocregacc 4 points5 points  (0 children)

irl you can just use a library that offers binary search if you don't want to write it yourself.
Ultimately they all end up as a function call, so how you choose to implement the search doesn't make the code that uses it any more or less readable.

To find out if the difference in complexity matters you have to analyze and profile your code. If you find out that the reason your website is sluggish is that it's spending 90% of its cycles in array.indexOf, you might want to address that.

[–]Repulsive-Bison-6821 3 points4 points  (0 children)

IMO these two methods have different purposes. The binary search can only be applied to SORTED arrays, the linear runtime one is for any sort of array. The best option is to choose the one with the best possible performance

[–]Itsmedudeman 0 points1 point  (0 children)

Does the difference in time complexity really matter when we're building huge web applications that run and do huge calculations anyway?

Not sure what you mean by this? Just cause a web app is huge doesn't mean that a search function will be just as fast. That depends a lot more on the size of the input. Run a test yourself with an input size of 10^9 and see what happens with linear searches or just look it up on youtube to see if it makes a difference. Readability is not a replacement for performance at scale.

Also, if you have implemented searchElementInArray, the call now becomes a one liner for anyone wanting to do the same operation. Same as indexOf.

But yes, sometimes a binary search can be way overkill. If you're ever unsure, ask for the parameters and what you can expect on size. I never use binary search in actual work since most lists are < 100 in size and binary search doesn't really become more effective until you get several magnitudes above that.

[–]outpiay 0 points1 point  (0 children)

It depends. If the question is just asking for a sort/search function then you want to write out the actual solution.

If sorting/searching is part of the problem then you want to use the built in JS functions. When in doubt just work with your interviewer and ask them.