Skip to content

Conversation

@rishigoswamy
Copy link

No description provided.

@super30admin
Copy link
Owner

Your solution for leetcode34.py is well-structured and correctly implements the two binary searches to find the first and last occurrence of the target. The logic for both searches is accurate, and you've handled the boundary conditions properly (e.g., checking if mid is at the start or end of the array).

Strengths:

  • You correctly used binary search to achieve O(log n) time complexity.
  • The code is clean and easy to follow.
  • You handled edge cases such as when the target is at the beginning or end.

Areas for improvement:

  1. Remove the initial assignment of mid (line 95) since it is immediately reassigned in the while loop. This is redundant and might cause confusion.
  2. Consider skipping the second binary search if the first search returns -1. This would make the solution slightly more efficient in the case where the target is not present.
  3. Use more descriptive variable names. For example, instead of first and second, use first_occurrence and last_occurrence to make the code self-documenting.

Example improvement:

class Solution:
    def searchRange(self, nums, target):
        first = -1
        low, high = 0, len(nums) - 1
        while low <= high:
            mid = (low + high) // 2
            if nums[mid] == target:
                if mid == 0 or nums[mid-1] != target:
                    first = mid
                    break
                else:
                    high = mid - 1
            elif nums[mid] > target:
                high = mid - 1
            else:
                low = mid + 1
        
        if first == -1:
            return [-1, -1]
            
        last = -1
        low, high = 0, len(nums) - 1
        while low <= high:
            mid = (low + high) // 2
            if nums[mid] == target:
                if mid == len(nums)-1 or nums[mid+1] != target:
                    last = mid
                    break
                else:
                    low = mid + 1
            elif nums[mid] > target:
                high = mid - 1
            else:
                low = mid + 1
        
        return [first, last]

This version avoids the second search if the target is not found and uses better variable names.

Overall, your solution is correct and efficient. The issues are minor and do not affect the correctness.

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