Can someone please help me in binary search. I am confused whether to use

--> l=0 , h = arr.size()-1 and m = (l+h)/2 and while(l<h)

--> l=0 , h = arr.size() and m = (l+h+1)/2 and while(l<h)

--> l=0 , h = arr.size()-1 and m = l+(h-l)/2 and while(l<h)

--> l=0 , h = arr.size()-1 and m = (l+h)/2 and while(l<=h)

It seems that in some cases some of the above give TLE. Can some experienced community member help me which I should use .

I think many of the beginners face this issue while implementing binary search . A little help would be appreciated

So basically there are confusion regarding

while(l<h) or while(l<=h) or while(h-l>1)

m=(l+h+1)/2 or m=l+(h-l)/2 or m=(l+h)/2

h=arr.size() or h=arr.size()-1

Just think what exactly you want to happen for intervals of size 1, 2 or 3.

You can watch my video here, https://www.youtube.com/watch?v=GU7DpgHINWQ.

In the description section of your video you recommended solving leetcode binary search problems. Actually I was solving this problem from leetcode : problem

In the discuss forum on leetcode : link the great

StefanPochmannexplained a rather new solution which I am unable to understand. Can you help me with that. Also nice video:)It's something unique for this problem so you won't use it in other problems anyway ;p the important thing is to understand when you should go to the right, when to the left.

What he does is he imagines that one part of the sequence is changed into -INF or +INF what tells you to go right or left respectively.

Yes. Thanks

StefanPochmannjust never fails to amaze me. His solutions are so concise and are like if himself set the question XD.Literally the best video on binary search .

Here is what I do:

The key is to think about what your binary searched values will look like (TTTTTFFFFFF? or opposite) and then about which one you want (first occurrence of T? last occurrence of F?) which mostly depends on the problem and how you defined true/false values. Then you can select either start = mid + 1 or end = mid — 1 in the LOGIC places I wrote. I select these by thinking about what happens at the end case (the destination where we have either TF or FT transition).

Thanks. The prefix suffix part is really helpful

I don't think that makes a difference.

PS: I wonder if the second implementation is correct?

What I do is one of 2 of the following, depending on the problem i'm solving:

or

So I start by writing $$$mid=(lo+hi)/2$$$ and when i write the rest of the while loop I add a +1 if I have $$$hi=mid-1$$$.

Hi, Can you please explain why

`mid = (lo+hi+1)/2`

and not`mid=(lo+hi)/2`

in the second implementation ??Thanks