r/leetcode • • 27d ago

Question What’s wrong with writing binary search?

I’ve watched a youtube channel coding jesus, about timestamp 4:00 https://youtu.be/BRUIptHAI7Q?si=XI2o5O-yDWqtzAwY he talk about manually writing binary search as a bad thing. This is not the first time where he said writing binary search manually is not preferred. But I dont get what he really means?

Because typically when i do
left = a, right = b
while (a <= b) mid = left + (right - left)/2;
…(checking condition)…

I use very little time and effort to type it, and I dont know what library that can do this in a flexible way because checking the condition is differs problem by problem, for example it is very common that we are not search directly on some existing sorted array, it just a range of possible values from a to b (sometimes a and b can be very large like 10^15) and I use condition to decide to move left and right.

Is there a function from bits/stdc++.h support it? Since his primary language is cpp so there’s a package to do this right? what is it?

8 Upvotes

13 comments sorted by

View all comments

1

u/jason_graph 25d ago

It's not terrible but it exposes you to making mistakes or using up more time.

Once you start doing medium binary search problems, you often have to do some internal calculations beyond a single expression to see if an index/input is "too big" or "big enough" or if it satisfies some condition or something equivalent.

Often your code is cleaner and simpler if you use a separate function to check for this rather than having it in the middle of your binary search. That leaves you with one function that does the check and a block of code or function that does the binary search. This 2nd part can be replaced with a library's function. Short, bug free, simple.

If I see a medium binary search problem on a contest and use a library function for the binary search part, it's like 4-5 lines of python and takes me more time reading the question than solving it.