C
C#2y ago
morry329#

✅ Gaps in understanding a LC solution

It's about comprehending this solution https://leetcode.com/problems/binary-search/solutions/3365281/binary-search-c/ Question 1: why is the condition for the while loop like this? left <= right, not left < right Question 2: why is this line of code located in the while loop, not outside of it? int middle = left + (right-left)/2; Question 3: why does int middle = left + (right-left)/2; compile and why int middle = (left + (right-left))/2; not?
LeetCode
Binary Search C# - Binary Search - LeetCode
View MaddiSwetha's solution of Binary Search on LeetCode, the world's largest programming community.
2 Replies
Anton
Anton2y ago
1: because in this case it would check the single number at that position. you can't be sure that exact number will be in the array right? you have to make sure by checking, even if it's the last remaining element 2: because left and right change each iteration? 3: the latter will overflow for larger indices, the former isn't prone to that it does compile, it's just that it's technically not perfectly correct
morry329#
morry329#OP2y ago
Thank you so much for the amazing explanation 🙌 I got it
Want results from more Discord servers?
Add your server