Skip to content

Instantly share code, notes, and snippets.

@ssaadh
Created February 27, 2023 19:57
Show Gist options
  • Save ssaadh/732befe82a6f024a12afbd31b755ba78 to your computer and use it in GitHub Desktop.
Save ssaadh/732befe82a6f024a12afbd31b755ba78 to your computer and use it in GitHub Desktop.
Hints when to Use Binary Search in an interview.. - When an array or matrix is sorted or partially sorted that might be a sign that you want to use binary search - When the O(N) solution is obvious or the interviewer is looking for faster than O(N). Key Takeaways: - Search Condition can be determined without comparing to the element's neighbors …
def binarySearch(nums, target):
"""
:type nums: List[int]
:type target: int
:rtype: int
"""
if len(nums) == 0:
return -1
lo, hi= 0, len(nums) - 1
while lo <= hi:
mid = (lo + hi) // 2
if nums[mid] == target:
return mid
elif nums[mid] < target:
lo = mid + 1
else:
hi = mid - 1
# End Condition: lo > hi
return -1
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment