Skip to content

Instantly share code, notes, and snippets.

@siddydutta
Last active November 20, 2021 05:27
Show Gist options
  • Save siddydutta/be1f08d330eeb8930289e8839b71f323 to your computer and use it in GitHub Desktop.
Save siddydutta/be1f08d330eeb8930289e8839b71f323 to your computer and use it in GitHub Desktop.
A Python template to solve problems involving binary search.
"""
A Python template to solve problems involving binary search.
Template based on this post: https://leetcode.com/problems/kth-smallest-number-in-multiplication-table/discuss/769704/Python-Clear-explanation-Powerful-Ultimate-Binary-Search-Template.-Solved-many-problems.
"""
def binary_search(array) -> int:
def condition(value) -> bool:
# Conditional logic based on question
# Returns true if current value satisfies requirements
# binary search will take care of finding the minimal val
return
left, right = 0, len(array)-1 # Include all possible elements
while left < right:
mid = left + (right-left) // 2 # To prevent overflow
if condition(mid):
right = mid
else:
left = mid + 1
return left # left is the minimal val satisfying condition, sometimes may left-1 is required
"""
Example usage of template
Problem: https://leetcode.com/problems/kth-smallest-number-in-multiplication-table/
Solution: https://github.com/siddydutta/Daily-LeetCoding-Challenges/blob/master/2021-11-November-LeetCoding-Challenge/Kth%20Smallest%20Number%20in%20Multiplication%20Table.py
"""
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment