Closest snack pair to budget
A nutrition app shows snack calories sorted ascending. A user wants to pick two different snacks whose combined calories land as close as possible to their remaining daily budget. Given the sorted list calories (length at least 2) and the budget, return the smallest achievable value of |sum - budget| over all pairs. Use converging pointers, not the O(n²) pair scan. Example: calories = [100, 150, 300, 500], budget = 420 gives 20 (100 + 300 = 400, off by 20; no pair gets closer).
Implement
closest_pair_gap(calories: list[int], budget: int) → intExamples
in
[[100,150,300,500],420]out20What a strong answer looks like
State your approach and its time/space complexity out loud before you optimize. Handle the edge cases (empty input, duplicates, overflow), and say why you chose this over the brute force. Green tests are the floor, not the grade.
0:00 of about 14 min
solution.py
InputExpectedGot
[[100,150,300,500],420]20not run yetsample