Code Room
CodingMediumcod-g1409
Subject Two pointersLevel Entry–Mid~14 minCommon in Algorithms & data structures interviewsIndustries Software development

Question

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) → int
Examples
in[[100,150,300,500],420]out20
What 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.

Vibe coding: describe the solution in plain language (or narrate it) and the coach grades your approach. Generating runnable code from your description is coming next.

Run or narrate your approach, then ask the coach.