Skip to content

Commit 1b68ef6

Browse files
committed
feat: add binary search on answer template with example use case
1 parent 791deb4 commit 1b68ef6

1 file changed

Lines changed: 66 additions & 0 deletions

File tree

Lines changed: 66 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,66 @@
1+
from typing import Callable
2+
3+
4+
def binary_search_on_answer(
5+
low: int, high: int, condition: Callable[[int], bool]
6+
) -> int:
7+
"""
8+
Generic Binary Search on Answer template.
9+
10+
Finds the minimum value in the range [low, high] that satisfies the condition.
11+
12+
The condition function must be monotonic:
13+
- False False False True True True
14+
15+
:param low: lower bound of search space
16+
:param high: upper bound of search space
17+
:param condition: function that returns True if mid is a valid answer
18+
19+
:return: smallest value that satisfies the condition
20+
21+
Examples:
22+
>>> def condition(x): return x * x >= 16
23+
>>> binary_search_on_answer(0, 10, condition)
24+
4
25+
26+
>>> def condition(x): return x >= 7
27+
>>> binary_search_on_answer(0, 10, condition)
28+
7
29+
"""
30+
answer = high
31+
32+
while low <= high:
33+
mid = low + (high - low) // 2
34+
35+
if condition(mid):
36+
answer = mid
37+
high = mid - 1
38+
else:
39+
low = mid + 1
40+
41+
return answer
42+
43+
44+
# Example1: minimum capacity to ship
45+
46+
def min_capacity_to_ship(weights: list[int], days: int) -> int:
47+
"""
48+
Find minimum capacity to ship packages within given days.
49+
50+
>>> min_capacity_to_ship([1,2,3,4,5,6,7,8,9,10], 5)
51+
15
52+
"""
53+
54+
def can_ship(capacity: int) -> bool:
55+
days_used = 1
56+
current = 0
57+
58+
for weight in weights:
59+
if current + weight > capacity:
60+
days_used += 1
61+
current = 0
62+
current += weight
63+
64+
return days_used <= days
65+
66+
return binary_search_on_answer(max(weights), sum(weights), can_ship)

0 commit comments

Comments
 (0)