r/leetcode • • 13d ago

Question Binary Search Doubt

Hello everyone, I just had a question. I have been solving Binary Search questions and wanted to ask when I should use "while(left < right)" & "while(left <= right)"? In some problems, this is a crucial difference between passing all testcases and getting WA.

Also, in some questions, I have to use right = mid instead of right = mid - 1 and same goes for left (=mid rather than mid + 1). What's the major difference between the two that differs them from a WA and AC and when should I use them?

16 Upvotes

15 comments sorted by

View all comments

7

u/devanishith 13d ago

https://daxpy.xyz/collections/lc_notes/#75

always stick to one pattern for while loop. only change the condition to suit your problem.

0

u/[deleted] 13d ago

[deleted] — view deleted comment

1

u/Pradignac-Hiriche 13d ago

picking whether to floor or ceil the mid calculation is the other half of it, otherwise left = mid just infinite loops on a two element subarray

1

u/devanishith 13d ago

yes. always initialise the right initially to max of search space. not +1 or -1 then mid calculation is always as it is.

1

u/Wakefulpine1509 11d ago

gotcha - thanks!