Pair Sequential Lab and Consultation Slots

Medium · Coding & Algorithms · Software Engineer · Technical Screen

Problem Statement

A medical scheduling backend receives raw 10-minute availability entries from clinicians within a single day and assembles bookable two-part visits consisting of a 30-minute "lab" slot followed by a 30-minute "consultation" slot.

Each entry in records is a dictionary:

{"provider_id": str, "type": str, "start": str, "end": str}

where "start" and "end" are zero-padded 24-hour "HH:MM" strings on the same calendar day ("00:00" through "23:59").

Process records according to these four stages:

  1. Filter & Deduplicate Raw Entries
    • Keep an entry only if "type" is "lab" or "consultation" (exact lowercase match).
    • Keep an entry only if it covers 10 minutes (end - start == 10 minutes) and both "start" and "end" sit on 10-minute clock marks (:00, :10, :20, :30, :40, :50).
    • Drop malformed entries and deduplicate repeated entries having the same (provider_id, type, start, end).
  2. Coalesce Touching Intervals
    • Partition valid 10-minute entries by (provider_id, type).
    • Within each (provider_id, type) bucket, combine adjacent or overlapping 10-minute entries into maximal unbroken time spans.
  3. Slice 30-Minute Bookable Slots
    • Across each merged span [W_start, W_end], emit every 30-minute slot [t, t + 30] starting at 10-minute increments (t = W_start, W_start + 10, ... while t + 30 <= W_end). Spans shorter than 30 minutes produce zero slots.
  4. Pair Lab & Consultation Slots
    • Combine every generated "lab" slot with every generated "consultation" slot (whether offered by the same clinician or different clinicians) whose gap wait_minutes = consultation.start - lab.end satisfies 0 <= wait_minutes <= 60.
    • Format each valid combination as: python { "lab": {"provider_id": str, "start": str, "end": str}, "consultation": {"provider_id": str, "start": str, "end": str}, "wait_minutes": int, }
    • Order the returned list ascending by:
      1. lab["start"]
      2. consultation["start"]
      3. lab["provider_id"]
      4. consultation["provider_id"]

Implement:

def find_appointment_pairs(records: list[dict]) -> list[dict]:

Examples

Example 1

records = [
    {"provider_id": "L10", "type": "lab", "start": "13:20", "end": "13:30"},
    {"provider_id": "L10", "type": "lab", "start": "13:30", "end": "13:40"},
    {"provider_id": "L10", "type": "lab", "start": "13:40", "end": "13:50"},
    {"provider_id": "L10", "type": "lab", "start": "13:50", "end": "14:00"},
    {"provider_id": "C20", "type": "consultation", "start": "14:00", "end": "14:10"},
    {"provider_id": "C20", "type": "consultation", "start": "14:10", "end": "14:20"},
    {"provider_id": "C20", "type": "consultation", "start": "14:20", "end": "14:30"},
]

Output:

[
    {
        "lab": {"provider_id": "L10", "start": "13:20", "end": "13:50"},
        "consultation": {"provider_id": "C20", "start": "14:00", "end": "14:30"},
        "wait_minutes": 10,
    },
    {
        "lab": {"provider_id": "L10", "start": "13:30", "end": "14:00"},
        "consultation": {"provider_id": "C20", "start": "14:00", "end": "14:30"},
        "wait_minutes": 0,
    },
]

Walk-through: "L10" merges into one 40-minute span 13:20–14:00, producing two 30-minute lab slots (13:20–13:50 and 13:30–14:00). "C20" merges into 14:00–14:30, producing one consultation slot (14:00–14:30). Both lab slots finish within 0..60 minutes before 14:00 (wait_minutes 10 and 0).

Example 2

records = [
    {"provider_id": "D1", "type": "lab", "start": "07:00", "end": "07:10"},
    {"provider_id": "D1", "type": "lab", "start": "07:00", "end": "07:10"},
    {"provider_id": "D1", "type": "lab", "start": "07:10", "end": "07:20"},
    {"provider_id": "D2", "type": "lab", "start": "07:10", "end": "07:20"},
    {"provider_id": "D2", "type": "lab", "start": "07:20", "end": "07:30"},
    {"provider_id": "D2", "type": "lab", "start": "07:30", "end": "07:40"},
    {"provider_id": "D3", "type": "consultation", "start": "08:40", "end": "08:50"},
    {"provider_id": "D3", "type": "consultation", "start": "08:50", "end": "09:00"},
    {"provider_id": "D3", "type": "consultation", "start": "09:00", "end": "09:10"},
    {"provider_id": "D4", "type": "consultation", "start": "08:50", "end": "09:00"},
    {"provider_id": "D4", "type": "consultation", "start": "09:00", "end": "09:10"},
    {"provider_id": "D4", "type": "consultation", "start": "09:10", "end": "09:20"},
]

Output:

[
    {
        "lab": {"provider_id": "D2", "start": "07:10", "end": "07:40"},
        "consultation": {"provider_id": "D3", "start": "08:40", "end": "09:10"},
        "wait_minutes": 60,
    }
]

Walk-through: After deduplicating "D1"'s repeated 07:00–07:10 block, "D1" only covers 07:00–07:20 (20 minutes, too short for a 30-minute lab). "D2" forms 07:10–07:40, which pairs with "D3" (08:40–09:10, exact 60-minute gap) while "D4" (08:50–09:20, 70-minute gap) exceeds the 60-minute cap.

Example 3

records = [
    {"provider_id": "L2", "type": "lab", "start": "15:00", "end": "15:10"},
    {"provider_id": "L2", "type": "lab", "start": "15:10", "end": "15:20"},
    {"provider_id": "L2", "type": "lab", "start": "15:20", "end": "15:30"},
    {"provider_id": "L1", "type": "lab", "start": "15:00", "end": "15:10"},
    {"provider_id": "L1", "type": "lab", "start": "15:10", "end": "15:20"},
    {"provider_id": "L1", "type": "lab", "start": "15:20", "end": "15:30"},
    {"provider_id": "L3", "type": "lab", "start": "15:00", "end": "15:10"},
    {"provider_id": "L3", "type": "lab", "start": "15:15", "end": "15:25"},
    {"provider_id": "L3", "type": "lab", "start": "15:20", "end": "15:30"},
    {"provider_id": "C9", "type": "consultation", "start": "15:50", "end": "16:00"},
    {"provider_id": "C9", "type": "consultation", "start": "16:00", "end": "16:10"},
    {"provider_id": "C9", "type": "consultation", "start": "16:10", "end": "16:20"},
]

Output:

[
    {
        "lab": {"provider_id": "L1", "start": "15:00", "end": "15:30"},
        "consultation": {"provider_id": "C9", "start": "15:50", "end": "16:20"},
        "wait_minutes": 20,
    },
    {
        "lab": {"provider_id": "L2", "start": "15:00", "end": "15:30"},
        "consultation": {"provider_id": "C9", "start": "15:50", "end": "16:20"},
        "wait_minutes": 20,
    },
]

Walk-through: "L3"'s off-grid 15:15–15:25 entry is discarded, leaving "L3" with two disconnected 10-minute blocks (15:00–15:10 and 15:20–15:30) and zero 30-minute labs. "L1" and "L2" both form 15:00–15:30 and pair with "C9" (15:50–16:20); "L1" sorts ahead of "L2" on the third sort key (lab["provider_id"]).

Constraints

  • 0 <= len(records) <= 2000
  • Every "start" and "end" value is a valid 24-hour "HH:MM" timestamp within "00:00"–"23:59"
  • "provider_id" and "type" are strings

Step-by-step walkthrough

  1. Understand the four-stage scheduling pipeline

    We receive raw 10-minute availability dictionaries {"provider_id", "type", "start", "end"} within a single day (00:00 to 23:59) and transform them through four clean stages:

    1. Validate & deduplicate: keep only "lab" or "consultation" entries whose start and end sit on 10-minute marks (:00, :10, ..., :50) with end - start == 10 minutes, dropping duplicate slots per (provider_id, type).
    2. Merge contiguous blocks: within each (provider_id, type) group, join touching 10-minute blocks into maximal continuous availability windows.
    3. Generate 30-minute appointments: slide a 30-minute window across each merged span in 10-minute steps.
    4. Match & sort pairs: pair every lab with every consultation starting 0 to 60 minutes after the lab ends, sorted by (lab.start, consultation.start, lab.provider_id, consultation.provider_id).

    Here is Example 1 drawn as a timeline:

    L10 (lab) raw blocks:        [13:20-13:30][13:30-13:40][13:40-13:50][13:50-14:00]
    Merged window:               [13:20 ------------------------------> 14:00]  (40 min)
    30-min lab options:          [13:20 ----------------> 13:50]
                                        [13:30 ----------------> 14:00]
    
    C20 (consultation) blocks:                                          [14:00..14:30]
    30-min consultation option:                                         [14:00->14:30]
    
    Waits to 14:00:              13:50 -> 14:00 is 10 min (valid: 0 <= 10 <= 60)
                                 14:00 -> 14:00 is  0 min (valid: 0 <=  0 <= 60)
    
  2. Step 1: Convert times to minutes, validate, and deduplicate

    Doing arithmetic directly on "HH:MM" strings is awkward because "09:40" plus 30 minutes crosses an hour boundary into "10:10". Instead, convert every time immediately into integer minutes since midnight: - "09:40" -> 9 * 60 + 40 = 580. - Because 60 is already a multiple of 10, checking start_min % 10 == 0 checks whether the :MM portion is 00, 10, 20, 30, 40, or 50!

    To group and deduplicate simultaneously, map each (provider_id, appt_type) pair to a Python set of valid start_min integers. Using (provider_id, appt_type) as the dictionary key guarantees two things: - Duplicate identical records for the same provider and type collapse into a single integer in the set. - Different providers (or "lab" vs "consultation" slots of the same provider) stay in separate buckets so they never accidentally merge together.

    APPOINTMENT_MINUTES = 30
    MAX_WAIT_MINUTES = 60
    VALID_TYPES = ("lab", "consultation")
    
    
    def to_minutes(hhmm: str) -> int:
        """Convert an 'HH:MM' 24-hour string into integer minutes since 00:00."""
        hours_str, minutes_str = hhmm.split(":")
        return int(hours_str) * 60 + int(minutes_str)
    
    
    def to_hhmm(total_minutes: int) -> str:
        """Format integer minutes since 00:00 as a zero-padded 'HH:MM' string."""
        hours = total_minutes // 60
        minutes = total_minutes % 60
        return f"{hours:02d}:{minutes:02d}"
    
    
    def collect_valid_blocks(records: list[dict]) -> dict:
        """Group valid, deduplicated 10-minute block start times by (provider_id, type)."""
        # groups: {(provider_id, appt_type): set of valid 10-minute start_minute ints}
        groups = {}
        for record in records:
            appt_type = record["type"]
            if appt_type not in VALID_TYPES:
                continue
    
            start_min = to_minutes(record["start"])
            end_min = to_minutes(record["end"])
    
            # Must be an exact 10-minute block aligned to 10-minute marks (60 is divisible by 10).
            if end_min - start_min != 10:
                continue
            if start_min % 10 != 0 or end_min % 10 != 0:
                continue
    
            group_key = (record["provider_id"], appt_type)
            if group_key not in groups:
                groups[group_key] = set()
            # Adding to a set automatically discards duplicate identical slots for the same provider.
            groups[group_key].add(start_min)
    
        return groups
    
  3. Step 2: Merge contiguous 10-minute blocks into windows

    For one (provider_id, appt_type) group, we sort its block_starts in ascending order and merge touching [start_min, start_min + 10] intervals into maximal [window_start, window_end] windows:

    Sorted block starts: 540 (09:00), 550 (09:10), 570 (09:30)
    
    1. 540 -> open [540, 550]
    2. 550 -> 550 <= 550 (back-to-back!) -> extend to [540, 560]
    3. 570 -> 570 >  560 (10-min gap!)   -> open new [570, 580]
    

    Notice the <= comparison (start_min <= windows[-1][1]): back-to-back blocks share a single boundary minute (550 == 550), so using < instead of <= would fail to merge any back-to-back slots at all!

    def merge_blocks(block_starts: set) -> list:
        """Merge sorted 10-minute blocks into maximal [window_start, window_end] windows."""
        # windows: list of [window_start, window_end] continuous availability intervals
        windows = []
        for start_min in sorted(block_starts):
            block_end = start_min + 10
            # Use <= so back-to-back blocks (e.g. [540, 550] and [550, 560]) merge into one window.
            if windows and start_min <= windows[-1][1]:
                windows[-1][1] = max(windows[-1][1], block_end)
            else:
                windows.append([start_min, block_end])
        return windows
    
  4. Step 3: Slide a 30-minute window in 10-minute steps

    Inside a continuous window [window_start, window_end], a 30-minute appointment can start at window_start, window_start + 10, window_start + 20, and so on, as long as current_start + 30 <= window_end: - A 20-minute window ([420, 440] for "D1" in Example 2) has 420 + 30 > 440, yielding 0 appointments. - A 30-minute window ([840, 870]) yields 1 appointment (840). - A 40-minute window ([800, 840]) yields 2 appointments (800 and 810) — remember to advance current_start += 10, not += 30!

    def generate_appointment_starts(window_start: int, window_end: int) -> list:
        """Slide a 30-minute appointment across [window_start, window_end] in 10-minute steps."""
        starts = []
        current_start = window_start
        # Step by 10 (not 30) so a 40-minute window yields both [s, s+30] and [s+10, s+40].
        while current_start + APPOINTMENT_MINUTES <= window_end:
            starts.append(current_start)
            current_start += 10
        return starts
    
  5. Step 4: Match labs to consultations with binary search

    Once we collect labs and consultations as (start_min, provider_id) tuples, a lab ending at lab_end = lab_start + 30 pairs with every consultation whose consult_start falls inside [lab_end, lab_end + 60].

    Instead of comparing every lab against every consultation (O(A * B)), we sort consultations by consult_start once and extract consultation_starts. For each lab, bisect.bisect_left(consultation_starts, lab_end) jumps in O(log B) steps directly to the first consultation starting at or after lab_end, and a while loop walks right until consult_start - lab_end > 60:

    Sorted consultation_starts:  [ 510,  560,  570,  600,  630,  640 ]
                                                ^               ^
                               lab_end = 570 ---+               +-- 640 - 570 = 70 > 60 (stop!)
                               bisect_left lands at index 2; loop collects 570, 600, 630.
    
    # Sort consultations by start_min so binary search can jump straight to each lab's end time.
    consultations.sort()
    consultation_starts = []
    for consult_start, _ in consultations:
        consultation_starts.append(consult_start)
    
    # matched_tuples: (lab_start, consult_start, lab_provider, consult_provider)
    matched_tuples = []
    for lab_start, lab_provider in labs:
        lab_end = lab_start + APPOINTMENT_MINUTES
        # bisect_left finds the first consultation with consult_start >= lab_end (wait >= 0).
        idx = bisect.bisect_left(consultation_starts, lab_end)
        while idx < len(consultations) and consultations[idx][0] - lab_end <= MAX_WAIT_MINUTES:
            consult_start, consult_provider = consultations[idx]
            matched_tuples.append((lab_start, consult_start, lab_provider, consult_provider))
            idx += 1
    
  6. Sort pairs, format `"HH:MM"`, and trace Example 1

    Look at the tuple layout we pushed into matched_tuples: (lab_start, consult_start, lab_provider, consult_provider)

    Its first three fields match the required sort order (lab start time, then consultation start time, then lab provider ID), and integer minutes sort chronologically (800 before 810). Placing consult_provider fourth breaks any tie when two consultation providers offer the exact same slot. After calling matched_tuples.sort(), we convert minutes back to "HH:MM" with to_hhmm (:02d preserves leading zeros like "07:10").

    Let's verify Example 1 end-to-end:

    1. collect_valid_blocks:
         ('L10', 'lab')          -> {800, 810, 820, 830}
         ('C20', 'consultation') -> {840, 850, 860}
    2. merge_blocks:
         ('L10', 'lab')          -> [[800, 840]]
         ('C20', 'consultation') -> [[840, 870]]
    3. generate_appointment_starts:
         labs          = [(800, 'L10'), (810, 'L10')]
         consultations = [(840, 'C20')]
    4. Match with bisect_left:
         lab (800, 'L10'), lab_end = 830 -> matches (840, 'C20'), wait = 840 - 830 = 10
         lab (810, 'L10'), lab_end = 840 -> matches (840, 'C20'), wait = 840 - 840 = 0
    5. Sort & format:
         (800, 840, 'L10', 'C20') -> L10 13:20-13:50 + C20 14:00-14:30, wait_minutes = 10
         (810, 840, 'L10', 'C20') -> L10 13:30-14:00 + C20 14:00-14:30, wait_minutes = 0
    
  7. Complete solution

    Putting all helpers and phases together gives the complete pipeline:

    from typing import Any, Dict, List, Optional, Set, Tuple
    
    import bisect
    
    APPOINTMENT_MINUTES = 30
    MAX_WAIT_MINUTES = 60
    VALID_TYPES = ("lab", "consultation")
    
    
    def to_minutes(hhmm: str) -> int:
        """Convert an 'HH:MM' 24-hour string into integer minutes since 00:00."""
        hours_str, minutes_str = hhmm.split(":")
        return int(hours_str) * 60 + int(minutes_str)
    
    
    def to_hhmm(total_minutes: int) -> str:
        """Format integer minutes since 00:00 as a zero-padded 'HH:MM' string."""
        hours = total_minutes // 60
        minutes = total_minutes % 60
        return f"{hours:02d}:{minutes:02d}"
    
    
    def collect_valid_blocks(records: list[dict]) -> dict:
        """Group valid, deduplicated 10-minute block start times by (provider_id, type)."""
        # groups: {(provider_id, appt_type): set of valid 10-minute start_minute ints}
        groups = {}
        for record in records:
            appt_type = record["type"]
            if appt_type not in VALID_TYPES:
                continue
    
            start_min = to_minutes(record["start"])
            end_min = to_minutes(record["end"])
    
            # Must be an exact 10-minute block aligned to 10-minute marks (60 is divisible by 10).
            if end_min - start_min != 10:
                continue
            if start_min % 10 != 0 or end_min % 10 != 0:
                continue
    
            group_key = (record["provider_id"], appt_type)
            if group_key not in groups:
                groups[group_key] = set()
            # Adding to a set automatically discards duplicate identical slots for the same provider.
            groups[group_key].add(start_min)
    
        return groups
    
    
    def merge_blocks(block_starts: set) -> list:
        """Merge sorted 10-minute blocks into maximal [window_start, window_end] windows."""
        # windows: list of [window_start, window_end] continuous availability intervals
        windows = []
        for start_min in sorted(block_starts):
            block_end = start_min + 10
            # Use <= so back-to-back blocks (e.g. [540, 550] and [550, 560]) merge into one window.
            if windows and start_min <= windows[-1][1]:
                windows[-1][1] = max(windows[-1][1], block_end)
            else:
                windows.append([start_min, block_end])
        return windows
    
    
    def generate_appointment_starts(window_start: int, window_end: int) -> list:
        """Slide a 30-minute appointment across [window_start, window_end] in 10-minute steps."""
        starts = []
        current_start = window_start
        # Step by 10 (not 30) so a 40-minute window yields both [s, s+30] and [s+10, s+40].
        while current_start + APPOINTMENT_MINUTES <= window_end:
            starts.append(current_start)
            current_start += 10
        return starts
    
    
    def find_appointment_pairs(records: list[dict]) -> list[dict]:
        # Phase 1-3: Validate, merge per (provider_id, type), and cut 30-minute appointments.
        # labs, consultations: lists of (start_min, provider_id) tuples
        labs = []
        consultations = []
    
        groups = collect_valid_blocks(records)
        for (provider_id, appt_type), block_starts in groups.items():
            for window_start, window_end in merge_blocks(block_starts):
                for start_min in generate_appointment_starts(window_start, window_end):
                    if appt_type == "lab":
                        labs.append((start_min, provider_id))
                    else:
                        consultations.append((start_min, provider_id))
    
        # Sort consultations by start_min so binary search can jump straight to each lab's end time.
        consultations.sort()
        consultation_starts = []
        for consult_start, _ in consultations:
            consultation_starts.append(consult_start)
    
        # Phase 4: Match each lab with consultations in [lab_end, lab_end + 60].
        # matched_tuples: (lab_start, consult_start, lab_provider, consult_provider)
        matched_tuples = []
        for lab_start, lab_provider in labs:
            lab_end = lab_start + APPOINTMENT_MINUTES
            # bisect_left finds the first consultation with consult_start >= lab_end (wait >= 0).
            idx = bisect.bisect_left(consultation_starts, lab_end)
            while idx < len(consultations) and consultations[idx][0] - lab_end <= MAX_WAIT_MINUTES:
                consult_start, consult_provider = consultations[idx]
                matched_tuples.append((lab_start, consult_start, lab_provider, consult_provider))
                idx += 1
    
        # Tuple field order matches the required sort: lab start, consultation start, lab provider
        # (plus consultation provider last to break any remaining ties deterministically).
        matched_tuples.sort()
    
        # Phase 5: Format sorted tuples into the required dictionary schema.
        pairs = []
        for lab_start, consult_start, lab_provider, consult_provider in matched_tuples:
            lab_end = lab_start + APPOINTMENT_MINUTES
            consult_end = consult_start + APPOINTMENT_MINUTES
            pairs.append({
                "lab": {
                    "provider_id": lab_provider,
                    "start": to_hhmm(lab_start),
                    "end": to_hhmm(lab_end),
                },
                "consultation": {
                    "provider_id": consult_provider,
                    "start": to_hhmm(consult_start),
                    "end": to_hhmm(consult_end),
                },
                "wait_minutes": consult_start - lab_end,
            })
        return pairs
    

    ✅ Submit now — all tests should pass.

Intuition & how it works

Picture each raw 10-minute availability entry as a short timeline tile on a clinician's schedule: we first toss out malformed or duplicate tiles, snap touching tiles for the same (provider_id, type) together using interval merging (sorting [start, end] intervals by start time and combining back-to-back ranges into one continuous span), and slide a 30-minute ruler across each merged span in 10-minute notches to list every bookable 30-minute slot. Once we have all 30-minute labs and consultations, a lab ending at lab_end only pairs with consultations starting in [lab_end, lab_end + 60]. By sorting consultations by start time, we use binary search (repeatedly halving a sorted array via bisect_left to locate the first consultation >= lab_end in O(log B) time) and walk forward only through valid matches.

Why do naive shortcuts fail? Computing time differences directly on "HH:MM" strings breaks across hour boundaries (adding 30 minutes to "13:40" is "14:10", not "13:70"). Counting raw records instead of deduplicating and merging intervals gets fooled by repeated slots (in Example 2, "D1" has three records covering only 20 unique minutes, yielding zero 30-minute labs) or off-grid gaps ("L3" in Example 3). And comparing every lab against every consultation with nested loops wastes work on consultations outside [lab_end, lab_end + 60].

Here is a compact trace of Example 1 after converting "HH:MM" into minutes since 00:00:

L10 lab blocks:           {800, 810, 820, 830} -> merged [800, 840] -> 30-min labs at 800, 810
C20 consultation blocks:  {840, 850, 860}      -> merged [840, 870] -> 30-min consult at 840

Lab 800..830: bisect_left([840], 830) -> 840; wait = 840 - 830 = 10 (0 <= 10 <= 60) -> MATCH
Lab 810..840: bisect_left([840], 840) -> 840; wait = 840 - 840 =  0 (0 <=  0 <= 60) -> MATCH

Complexity

Let R be len(records), A and B be the numbers of generated 30-minute lab and consultation appointments (note A + B <= R, because every 30-minute appointment starts on a distinct valid 10-minute block), and P be the number of valid pairs returned.

  • Time: O(R log R + P log P). Validating and grouping R records into sets takes O(R) average time; sorting each group's blocks and sorting the B consultations takes O(R log R) total; for each of the A labs, bisect_left takes O(log B) and the inner while loop advances once per emitted match (O(A log B + P)); finally, sorting the P matched tuples takes O(P log P).
  • Space: O(R + P). The grouped block sets, merged windows, and labs/consultations lists hold at most O(R) entries in total, while matched_tuples and pairs store the P output items (note that P can be up to O(R^2) when many clinicians offer overlapping lab and consultation windows, so output construction dominates when P is large).

Edge cases

  • Empty input or windows shorter than 30 minutes: Returns [] cleanly when no clinician reaches 30 contiguous minutes (as with "D1"'s 20-minute span in Example 2 and "L3"'s split 10-minute spans in Example 3).
  • Malformed/invalid records: Wrong types or wrong capitalization ("Lab", "consult"), durations other than 10 minutes ("10:20" to "10:40"), or off-grid minutes ("15:15" to "15:25" in Example 3) are discarded before merging so they never bridge a gap between valid blocks.
  • Duplicate records: Storing starts in a set per (provider_id, type) ensures repeated records ("D1" in Example 2) neither artificially extend a window nor emit duplicate pairs.
  • Inclusive wait-window boundaries (0 and 60 minutes): bisect_left(..., lab_end) includes consult_start == lab_end (wait == 0 in Example 1), and <= MAX_WAIT_MINUTES includes wait == 60 ("D3" in Example 2) while stopping at 70 ("D4").
  • Same clinician for both visits vs different clinicians merging: One clinician can offer a lab 08:00-08:30 and consultation 08:30-09:00 (wait == 0), while D1 07:00-07:20 + D2 07:20-07:30 stay in separate groups and never form a fake 30-minute window.
  • Early-morning leading zeros: f"{hours:02d}:{minutes:02d}" formats 0 as "00:00" and 430 as "07:10", never "0:0" or "7:10".

Common mistakes

  • Using < instead of <= when merging intervals: Back-to-back blocks [800, 810] and [810, 820] meet at 810 == 810; < treats them as disjoint and keeps every window 10 minutes long.
  • Advancing appointment starts by 30 instead of 10: A 40-minute window 13:20-14:00 contains two overlapping 30-minute options (13:20-13:50 and 13:30-14:00), not one.
  • Grouping by provider_id alone: Merging "lab" and "consultation" blocks of the same clinician into one untyped window invents slots the clinician never offered.
  • Counting records instead of unique minutes: Three records for "D1" in Example 2 contain a duplicate 07:00-07:10, covering only 20 minutes (07:00-07:20).
  • Off-by-one wait bounds: Writing 0 < wait < 60 instead of 0 <= wait <= 60 drops back-to-back (wait == 0) and exact one-hour (wait == 60) pairs.

Alternative approaches

  • Bucket consultations by 10-minute start mark (avoids both binary search and final sort): Because every valid start is a multiple of 10, a lab ending at lab_end can only match consultations starting at the seven exact marks lab_end, lab_end + 10, ..., lab_end + 60. Grouping labs by lab_start (with sorted clinician IDs) and consultations by consult_start (with sorted clinician IDs), then iterating lab_start ascending -> offset in (0, 10, ..., 60) -> lab_provider ascending -> consult_provider ascending emits all P pairs already in exact sorted order in O(R log R + P) time!
  • Two-pointer sliding window: Sort both labs and consultations by time; maintain [left, right) consultation pointers that only move forward as lab_end increases, finding valid ranges in O(A + B) pointer moves before building pairs.

Follow-up questions

  • If availability spans several months and produces tens of thousands of 30-minute slots, how can you speed up pairing and avoid sorting a massive intermediate list? Convert timestamps to integer minutes since a fixed epoch (such as day_index * 1440 + minute_of_day) and index consultations in a hash map keyed by exact 10-minute start timestamp ({start_epoch_min: sorted_providers}). Each lab ending at lab_end checks at most 7 hash keys (lab_end + 0, +10, ..., +60) in O(1) time each instead of binary searching across months of slots, and emitting pairs in (lab_start, offset, lab_provider, consult_provider) order eliminates the O(P log P) sort completely. You can also partition by day in parallel, since day D's labs only ever reach consultations on day D or up to 01:20 on day D + 1.
  • What changes are needed if shifts and 30-minute appointments are allowed to cross midnight into the following day? Each record needs an explicit calendar date or full ISO-8601 start/end timestamp so boundaries map onto monotonically increasing epoch minutes (day_number * 1440 + hh * 60 + mm). On that continuous timeline, a 23:50 to 00:00 (next day) block naturally has end - start == 10, merges seamlessly with 00:00-00:20 into a cross-midnight 30-minute slot 23:50-00:20, and formats back into (date, HH:MM) on output without changing the merge or pairing logic.
  • Suppose clinic policy forbids the same clinician from handling both legs of a visit — how would you enforce that rule without hurting time complexity? Inside the inner matching loop, skip any candidate with if consult_provider == lab_provider: continue before appending the pair. Because a single clinician's merged windows do not overlap, lab_provider can appear at most once at each of the 7 start marks [lab_end, lab_end + 10, ..., lab_end + 60] — so each lab skips at most 7 entries across the entire loop, keeping total matching time O(A log B + P).

Follow-up questions

Similar questions

More Assort Health interview questions

All 1 Assort Health questions →