Skip to content

[IMP] Binary-Search-2#2308

Open
amitmittal117 wants to merge 1 commit intosuper30admin:masterfrom
amitmittal117:master
Open

[IMP] Binary-Search-2#2308
amitmittal117 wants to merge 1 commit intosuper30admin:masterfrom
amitmittal117:master

Conversation

@amitmittal117
Copy link

No description provided.

@super30admin
Copy link
Owner

For the first problem (Find First and Last Position):

  • Your solution is well-structured and efficient. The use of a single helper function with a flag to differentiate between the first and last search is a good design choice.
  • However, note that the calculation of mid is unconventional. While it is mathematically equivalent to the standard method, it is more common to write mid = low + (high - low) // 2 for clarity. This avoids confusion for other readers.
  • Also, consider adding comments to explain the purpose of the isFirst flag and the logic within the binary search for better maintainability.

For the second problem (Find Minimum in Rotated Sorted Array):

  • Your current solution does not correctly find the minimum in all cases. For example, test with [3,4,5,1,2]:
    • Initially, low=0, high=4, mid=2. Since nums[0]=3 <= nums[2]=5, you set lowest=min(5001,3)=3 and set low=3.
    • Then, low=3, high=4, mid=3. Now, nums[3]=1 <= nums[3]=1? Actually, you should check the sorted part. The standard approach is to compare the middle element with the right end to determine which half is sorted, and then move accordingly.
  • I recommend revising the algorithm. The common approach is to compare the mid element with the right element. If nums[mid] > nums[high], then the minimum must be in the right half (mid+1 to high). Otherwise, it is in the left half (low to mid). This ensures you always narrow down to the unsorted part where the minimum lies.
  • Here is a corrected version for your reference:
    def findMin(self, nums: List[int]) -> int:
        low, high = 0, len(nums) - 1
        while low < high:
            mid = (low + high) // 2
            if nums[mid] > nums[high]:
                low = mid + 1
            else:
                high = mid
        return nums[low]
  • This approach efficiently finds the minimum by always moving towards the unsorted part.

Overall, you have a good understanding of binary search, but need to ensure the logic is correct for all edge cases. Practice more problems to strengthen your skills.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants