Skip to content

Instantly share code, notes, and snippets.

@sashadev-sky
Last active March 27, 2026 06:04
Show Gist options
  • Select an option

  • Save sashadev-sky/a2bc6b4073e2d94767f13a61b979c3c4 to your computer and use it in GitHub Desktop.

Select an option

Save sashadev-sky/a2bc6b4073e2d94767f13a61b979c3c4 to your computer and use it in GitHub Desktop.
GLOBAL TEMPLATE: "Find first true"
from collections.abc import Callable
def binary_search(array: list[int], condition: Callable[[int], bool]) -> int:
left, right = 0, len(array) # insertion point may be after last element
# half-open interval [left, right) so no candidates when left === right
while left < right:
mid = (left + right) // 2
if condition(mid): # monotonic condition
right = mid # mid might still be the first true
else:
left = mid + 1
# if not found, inserting at left maintains sorted order
return left
const binarySearch = (length: number, condition: (idx: number) => boolean): number => {
let [left, right] = [0, length]; // insertion point may be after the last element
// half-open interval [left, right) so no candidates when left === right
while (left < right) {
const mid = Math.floor((left + right) / 2);
if (condition(mid)) { // monotonic condition
right = mid; // mid might still be the first true
} else {
left = mid + 1;
}
}
// if not found, inserting `target` at `left` maintains order
return left;
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment