Skip to content

Instantly share code, notes, and snippets.

@inside-code-yt
Created February 6, 2023 11:41
Show Gist options
  • Save inside-code-yt/a6f680f81cfc543926c21f4b756fec19 to your computer and use it in GitHub Desktop.
Save inside-code-yt/a6f680f81cfc543926c21f4b756fec19 to your computer and use it in GitHub Desktop.
def find_start(arr, target):
if arr[0] == target:
return 0
left, right = 0, len(arr)-1
while left <= right:
mid = (left+right)//2
if arr[mid] == target and arr[mid-1] < target:
return mid
elif arr[mid] < target:
left = mid+1
else:
right = mid-1
return -1
def find_end(arr, target):
if arr[-1] == target:
return len(arr)-1
left, right = 0, len(arr)-1
while left <= right:
mid = (left+right)//2
if arr[mid] == target and arr[mid+1] > target:
return mid
elif arr[mid] > target:
right = mid-1
else:
left = mid+1
return -1
def first_and_last(arr, target):
if len(arr) == 0 or arr[0] > target or arr[-1] < target:
return [-1, -1]
start = find_start(arr, target)
end = find_end(arr, target)
return [start, end]
if __name__ == '__main__':
arr = [2, 4, 5, 5, 5, 5, 5, 7, 9, 9]
target = 5
print(first_and_last(arr, target))
# Output:
# [2, 6]
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment