Skip to content

Latest commit

 

History

History
40 lines (36 loc) · 1.19 KB

34. First and Last in Sorted Array.md

File metadata and controls

40 lines (36 loc) · 1.19 KB

34. Find First and Last Position of Element in Sorted Array (Medium)

  • find left bound using >=
  • find right bound using condition <=
class Solution:
    def searchRange(self, nums: List[int], target: int) -> List[int]:
        if not nums:
            return [-1, -1]
        left, right = 0, len(nums) - 1
        count = 0
        start, end = -1, -1
        # find the left bound using >=
        while(left <= right):
            mid = (left + right) // 2
            # shift to the right so will find the end.
            if nums[mid] == target:
                end = mid
                left = mid + 1
            elif nums[mid] < target:
                left = mid + 1
            else:
                right = mid -1
        
        left, right = 0, len(nums) - 1
        # find the right bound using <=
        while(left <= right):
            mid = (left + right) // 2
            if nums[mid] == target:
                # shift to the left so will find the start.
                start = mid
                right = mid - 1
            elif nums[mid] > target:
                right = mid - 1
            else:
                left = mid + 1
        
        return[start, end]