Skip to content

Instantly share code, notes, and snippets.

@nhudinhtuan
Last active April 1, 2020 10:22
Show Gist options
  • Save nhudinhtuan/402e7d5eb110fafc0e870bd62dd99195 to your computer and use it in GitHub Desktop.
Save nhudinhtuan/402e7d5eb110fafc0e870bd62dd99195 to your computer and use it in GitHub Desktop.
Binary search - find the first position
def find_first_pos(arr, target):
left = 0
right = len(arr) - 1
first_position = -1 # keep track of the latest valid mid position
while left <= right:
mid = left + (right - left) // 2
if arr[mid] == target:
first_position = mid
right = mid - 1 # continue searching to the left
elif arr[mid] < target:
left = mid + 1
else:
right = mid - 1
return first_position
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment