Last active
March 27, 2026 06:04
-
-
Save sashadev-sky/a2bc6b4073e2d94767f13a61b979c3c4 to your computer and use it in GitHub Desktop.
GLOBAL TEMPLATE: "Find first true"
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| 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 |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| 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