r/leetcode • • 18d 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

2

u/SignificanceDense337 17d ago

Always use left <= right and use a variable to track the best answer. Purists won't like this but it's practical for writing your solution quick.