Skip to content

Instantly share code, notes, and snippets.

@hongtaoh
Created October 9, 2024 22:20
Show Gist options
  • Save hongtaoh/6310e175e148243ce751f9ae58ab8ea8 to your computer and use it in GitHub Desktop.
Save hongtaoh/6310e175e148243ce751f9ae58ab8ea8 to your computer and use it in GitHub Desktop.
Solution to Leetcode 34 Find First and Last Position of Element in Sorted Array
class Solution:
def searchRange(self, nums: List[int], target: int) -> List[int]:
left = self.binSearch(nums, target, True)
right = self.binSearch(nums, target, False)
return [left, right]
# modified binary search algorithm
def binSearch(self, nums, target, leftBiased):
l = 0
r = len(nums) - 1
i = -1
while l<=r:
m = (l+r)//2
if nums[m] < target:
l = m+1
elif nums[m] > target:
r = m-1
else:
i = m
if leftBiased:
r = m-1
else:
l = m+1
return i
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment