Pair Lab Visits with Follow-Up Consultations from 10-Minute Slots
Greedy & IntervalsAuto-graded · 19 test casesLast updated
Validate and merge 10-minute availability slots, expand them into 30-minute visits, and list every lab-then-consultation pairing with a wait of 0 to 60 minutes.
Lab-then-Consultation Booking
A clinic sells a combined visit made of two appointments: a "lab" appointment first, then a "consultation" appointment later the same day. Providers publish their availability as many small 10-minute slots. Your job is to turn those slots into real 30-minute appointments and list every valid lab/consultation pairing.
Input
slots is a list of dictionaries. Each has the shape
{"provider_id": str, "type": str, "start": "HH:MM", "end": "HH:MM"}
Times use the 24-hour clock.
Processing rules
1. Keep only usable slots. A slot is usable only if all of the following hold:
typeis exactly"lab"or"consultation".- Both
startandendhave a minute part that is a multiple of 10 (00,10,20,30,40,50). endis exactly 10 minutes afterstart. A slot that crosses midnight, such as23:50to00:00, is therefore not usable.
Skip every other record (including records with missing fields or malformed values). If the same provider lists the identical slot with the same type more than once, count it only once.
2. Merge slots. Within each (provider_id, type) group, join slots that overlap or touch end-to-start into maximal continuous windows. For example, 09:00-09:10 and 09:10-09:20 become 09:00-09:20.
3. Create 30-minute appointments. In every merged window, create each appointment that is exactly 30 minutes long, starts on a 10-minute step, and lies entirely inside the window. A window 09:00-09:40 gives 09:00-09:30 and 09:10-09:40. A window shorter than 30 minutes gives nothing. Appointments can never span a gap between two windows.
4. Pair appointments. Form a pair for every lab appointment L and every consultation appointment C where
0 <= C.start - L.end <= 60 (in minutes)
Both bounds are inclusive. The two appointments may belong to the same provider if that provider offers both types. wait_minutes is C.start - L.end.
Output
Return a list of dictionaries, one per pair, shaped like
{
"lab": {"provider_id": str, "start": "HH:MM", "end": "HH:MM"},
"consultation": {"provider_id": str, "start": "HH:MM", "end": "HH:MM"},
"wait_minutes": int
}
Times are zero-padded HH:MM strings. Sort the list by these keys, in order:
- lab start time
- consultation start time
- lab
provider_id(ordinary string comparison) - consultation
provider_id
If no pair exists, return an empty list.
Constraints
0 <= len(slots) <= 2000- All times lie within a single day (
00:00to23:59). - Time strings are intended to be in
HH:MMform, but invalid records must be ignored as described above. - The number of output pairs may be large, so avoid comparing every lab against every consultation when you can locate the matching consultations directly.
Examples
Example 1
Input: build_visit_pairs([{'provider_id': 'P1', 'type': 'lab', 'start': '09:00', 'end': '09:10'}, {'provider_id': 'P1', 'type': 'lab', 'start': '09:10', 'end': '09:20'}, {'provider_id': 'P1', 'type': 'lab', 'start': '09:20', 'end': '09:30'}, {'provider_id': 'P1', 'type': 'lab', 'start': '09:30', 'end': '09:40'}, {'provider_id': 'P2', 'type': 'consultation', 'start': '10:00', 'end': '10:10'}, {'provider_id': 'P2', 'type': 'consultation', 'start': '10:10', 'end': '10:20'}, {'provider_id': 'P2', 'type': 'consultation', 'start': '10:20', 'end': '10:30'}])
Output: [{'lab': {'provider_id': 'P1', 'start': '09:00', 'end': '09:30'}, 'consultation': {'provider_id': 'P2', 'start': '10:00', 'end': '10:30'}, 'wait_minutes': 30}, {'lab': {'provider_id': 'P1', 'start': '09:10', 'end': '09:40'}, 'consultation': {'provider_id': 'P2', 'start': '10:00', 'end': '10:30'}, 'wait_minutes': 20}]
Example 2
Input: build_visit_pairs([{'provider_id': 'A', 'type': 'lab', 'start': '08:00', 'end': '08:10'}, {'provider_id': 'A', 'type': 'lab', 'start': '08:20', 'end': '08:30'}, {'provider_id': 'B', 'type': 'consultation', 'start': '09:00', 'end': '09:10'}, {'provider_id': 'B', 'type': 'consultation', 'start': '09:10', 'end': '09:20'}, {'provider_id': 'B', 'type': 'consultation', 'start': '09:20', 'end': '09:30'}])
Output: []
Example 3
Input: build_visit_pairs([{'provider_id': 'P', 'type': 'lab', 'start': '12:00', 'end': '12:10'}, {'provider_id': 'P', 'type': 'lab', 'start': '12:00', 'end': '12:10'}, {'provider_id': 'P', 'type': 'lab', 'start': '12:10', 'end': '12:20'}, {'provider_id': 'Q', 'type': 'consultation', 'start': '13:00', 'end': '13:10'}, {'provider_id': 'Q', 'type': 'consultation', 'start': '13:10', 'end': '13:20'}, {'provider_id': 'Q', 'type': 'consultation', 'start': '13:20', 'end': '13:30'}])
Output: []
Hints
Hint 1
Convert every time to minutes since midnight right away, and do all comparisons and arithmetic on integers rather than strings.
Hint 2
Collect valid slots in a set per (provider, type) to remove duplicates, then sort and sweep to merge. Treat a slot that starts exactly where the current window ends as part of that window.
Hint 3
Sort all consultation appointments by start time. For each lab ending at time e, the matching consultations are those with start in [e, e + 60], which form one contiguous range you can find with two binary searches.
Worked solution
Medium Try it yourself first — then compare your approach, complexity and edge cases.
Approach
Work in four stages and use integer minutes throughout.
- Validate and deduplicate. Convert each
HH:MMstring to minutes since midnight. Keep a record only if its type islaborconsultation, both times are multiples of 10 minutes, andend - start == 10. Store the kept(start, end)tuples in a set per(provider_id, type)so duplicates disappear. - Merge. Sort each group's slots and sweep through them. If a slot starts at or before the current window's end, extend the window. Otherwise start a new one. Using "at or before" is what joins back-to-back slots.
- Generate appointments. For a window
[ws, we), emit appointments starting atws, ws+10, ...up to and includingwe - 30. Windows shorter than 30 minutes produce an empty range. - Pair. Sort all consultation appointments by start time. For a lab ending at
e, valid consultations have start in[e, e + 60]. In a sorted list these form one contiguous block, found withbisect_left(starts, e)andbisect_right(starts, e + 60). Build the pairs from that block and sort them by(lab start, consultation start, lab provider, consultation provider).
Why it is correct
- A minute value that is a multiple of 10 makes the total minutes a multiple of 10, because hours contribute multiples of 60. The check
end - start == 10rejects zero-length, reversed, longer, and midnight-crossing slots (00:00parses to 0, so23:50-00:00fails). - The sweep merge keeps the standard invariant: after sorting by start, any slot that touches or overlaps the current window must extend it, and any slot starting strictly later opens a new maximal window.
- Within a maximal window every 10-minute-aligned 30-minute interval is fully covered, and nothing outside a window is covered, so the generated appointments are exactly the bookable ones.
- The inclusive bounds of the wait rule match the two bisect calls, so waits of exactly 0 and exactly 60 are included.
- The sort key includes the consultation provider as a final tie-break, which makes the order fully deterministic. The lab end and consultation end are determined by their starts, so they add nothing.
Complexity
Let R be the number of records, L and C the numbers of generated lab and consultation appointments, and P the number of output pairs.
- Time: O(R log R) for grouping, sorting and merging, plus O(L + C) for generation, O(C log C + L log C) for locating matches, and O(P log P) to sort the output.
- Space: O(R + L + C + P).
- P can reach L × C, and it is inherent in the output size.
Reference solution
from bisect import bisect_left, bisect_right
def build_visit_pairs(slots: list[dict]) -> list[dict]:
def to_minutes(text):
if not isinstance(text, str) or len(text) != 5 or text[2] != ':':
return None
try:
h = int(text[:2])
m = int(text[3:])
except ValueError:
return None
if not (0 <= h <= 23 and 0 <= m <= 59):
return None
return h * 60 + m
def to_text(total):
return f'{total // 60:02d}:{total % 60:02d}'
# Step 1: validate and deduplicate
groups = {}
for rec in slots:
if not isinstance(rec, dict):
continue
provider = rec.get('provider_id')
kind = rec.get('type')
if not isinstance(provider, str) or kind not in ('lab', 'consultation'):
continue
s = to_minutes(rec.get('start'))
e = to_minutes(rec.get('end'))
if s is None or e is None:
continue
if s % 10 != 0 or e % 10 != 0 or e - s != 10:
continue
groups.setdefault((provider, kind), set()).add((s, e))
# Steps 2 and 3: merge into windows, then cut 30-minute appointments
appts = {'lab': [], 'consultation': []}
for (provider, kind), items in groups.items():
windows = []
for s, e in sorted(items):
if windows and s <= windows[-1][1]:
windows[-1] = (windows[-1][0], max(windows[-1][1], e))
else:
windows.append((s, e))
for ws, we in windows:
for st in range(ws, we - 30 + 1, 10):
appts[kind].append((st, st + 30, provider))
# Step 4: pair using binary search over consultations sorted by start
consults = sorted(appts['consultation'])
c_starts = [c[0] for c in consults]
found = []
for l_start, l_end, l_prov in appts['lab']:
lo = bisect_left(c_starts, l_end)
hi = bisect_right(c_starts, l_end + 60)
for c_start, c_end, c_prov in consults[lo:hi]:
key = (l_start, c_start, l_prov, c_prov, l_end, c_end)
out = {
'lab': {
'provider_id': l_prov,
'start': to_text(l_start),
'end': to_text(l_end),
},
'consultation': {
'provider_id': c_prov,
'start': to_text(c_start),
'end': to_text(c_end),
},
'wait_minutes': c_start - l_end,
}
found.append((key, out))
found.sort(key=lambda x: x[0])
return [out for _, out in found]