Add Kotlin implementation to find missing number in a list#1333
Add Kotlin implementation to find missing number in a list#1333Balaviknesh wants to merge 1 commit intosuper30admin:masterfrom
Conversation
|
Strengths:
Areas for Improvement:
To fix this, you should use the fact that in a complete array without duplicates, the value at index i should be i + 1. So, you can check if the value at mid is equal to mid + 1. If it is, then the missing number is to the right; otherwise, it's to the left. This is a common approach. Here is a corrected version of the binary search: This will work for arrays that start at 1. However, if the array does not start at 1 (meaning the missing number is 1), then the first element will be 2. At index0, the value is 2, which is not equal to 1 (0+1). So, the binary search would correctly identify that the missing number is on the left. But note: if the array does not start at 1, then the entire array is shifted. Actually, the problem assumes the array should contain numbers from 1 to n, so if the first element is not 1, then 1 is missing. So, you can first check if the first element is 1. If not, return 1. Similarly, if the last element is not n (which is list.size + 1), then the missing number is n. So, you should check these edge cases first. Revised plan:
Example: Then, inside the binary search, we assume that the missing number is between the first and last. The binary search checks for the point where the value is not equal to index+1. So, the code should be: This should handle all cases. |
No description provided.