Consecutive-Range Handoff Pairs for Interval Coverage
Greedy & IntervalsAuto-graded · 18 test casesLast updated
Tests interval reasoning and efficient pairing: find all unordered listing pairs whose consecutive availability windows together cover a full date range.
Consecutive-Range Handoff Pairs
You are given a collection of named listings. Each listing has an availability schedule: a list of individual day numbers on which it is open. You are also given a target window defined by a first day s and a last day e, both inclusive.
A handoff pair is an unordered pair of two distinct listings (X, Y) such that some split point t exists with s ≤ t < e where:
- Listing
Xis available on every day fromsthroughtwith no gaps, and - Listing
Yis available on every day fromt + 1throughewith no gaps.
Note that either listing may cover more than its required segment — what matters is that the required days are all present and contiguous. Each valid unordered pair must appear in the output exactly once, with the two listing names sorted alphabetically within the pair.
Return the list of all such pairs, sorted lexicographically.
What counts as a valid consecutive block
A listing covers a segment [a, b] consecutively if every integer from a to b inclusive appears in its availability list. Gaps anywhere in that range disqualify it for that role.
Constraints
1 ≤ number of listings ≤ 500- Each availability list contains between
0and10 000integers. - Day numbers are positive integers; duplicates within a single listing's availability list are allowed in the input and should be treated as a single occurrence.
1 ≤ s ≤ e ≤ 10 000- If
s == eors > e, no valid split point exists — return an empty list. - A listing may qualify as both the first and the second segment partner in different pairs.
- A listing cannot be paired with itself.
- If no valid pair exists, return an empty list.
Examples
Example 1
Input: find_handoff_pairs({'A': [1, 2, 3, 6, 7, 10, 11], 'B': [3, 4, 5, 6, 8, 9, 10, 13], 'C': [7, 8, 9, 10, 11]}, 3, 11)
Output: [['B', 'C']]
Example 2
Input: find_handoff_pairs({'A': [1, 2, 3, 4], 'B': [5, 6, 7, 8], 'C': [2, 3, 4, 5, 6, 7, 8]}, 1, 8)
Output: [['A', 'B'], ['A', 'C']]
Example 3
Input: find_handoff_pairs({'A': [1, 2, 3], 'B': [1, 2, 3], 'C': [4, 5, 6]}, 1, 6)
Output: [['A', 'C'], ['B', 'C']]
Hints
Hint 1
For each listing, you only need two numbers: how far its consecutive run from day `s` reaches (its 'prefix reach'), and where its consecutive run back from day `e` begins (its 'suffix start'). Everything else about the listing is irrelevant.
Hint 2
A pair (X, Y) is valid if X's prefix reach plus one is at least Y's suffix start — in other words, X hands off no later than Y can pick up. Check both orderings (X first, then Y first) since either listing can play either role.
Hint 3
To avoid checking every pair against every possible split day, reduce the problem to comparing two integers per pair. Sorting candidates by their suffix-start value and using binary search lets you find all matching partners for a given prefix-reach in O(log N) rather than O(N).
Worked solution
Medium Try it yourself first — then compare your approach, complexity and edge cases.
Approach
Core observation
Walking through every possible split day t for every pair is expensive. Instead, reduce each listing to at most two numbers:
- Prefix reach: if the listing includes day
s, walk forward fromsuntil the consecutive run breaks oreis passed. The last day reached is the prefix reach. Ifsis absent, the listing cannot play the first-half role. - Suffix start: if the listing includes day
e, walk backward fromeuntil the run breaks orsis passed. The first day reached is the suffix start. Ifeis absent, the listing cannot play the second-half role.
Validity condition
A pair (X, Y) with X taking the first half and Y the second is valid when:
prefix_reach[X] + 1 >= suffix_start[Y]
This says X's run reaches far enough that Y can continue from there to cover the rest of the window. The split point t can be chosen as any day in the overlap — its existence is guaranteed by the inequality.
For each unordered pair {X, Y}, check both orderings (X first or Y first). If either passes, include the pair once with names in alphabetical order.
Why this is correct
(⇒) If a valid t exists, then X covers s..t, so its prefix reach is at least t. Y covers t+1..e, so its suffix start is at most t+1. Therefore prefix_reach[X] + 1 ≥ t + 1 ≥ suffix_start[Y].
(⇐) If prefix_reach[X] + 1 ≥ suffix_start[Y], pick t = prefix_reach[X]. Then t ≥ s (the run started at s), t < e (the reach is capped at e - 1 because Y starts no later than prefix_reach[X] + 1 ≤ e), X covers s..t, and Y covers from suffix_start[Y] ≤ t + 1 through e, so Y covers t+1..e.
Edge cases
s >= e: no split point can exist; return[]immediately.- A listing missing
scontributes no prefix reach; missingecontributes no suffix start. Such listings can still participate in the other role. - If both listings have identical availability, both orderings may be valid; the pair still appears only once.
- A single listing covering the entire window
[s, e]holds both a prefix reach ofeand a suffix start ofs, so it can pair with any other listing that covers either boundary — they will together cover the range with any split point. - Duplicate day numbers in the input are collapsed via a set before any traversal.
Complexity
Let N be the number of listings and L the maximum length of any availability list.
- Preprocessing: converting each list to a set is O(L). Walking the run is O(R) where R = e − s + 1. Total: O(N · (L + R)).
- Pair enumeration: O(N²) pairs, each checked in O(1).
- Overall time: O(N · (L + R) + N²).
- Space: O(N · L) for the sets, O(N) for the two scalar maps, O(P) for the output where P is the number of valid pairs.
The naive approach of testing every split day for every pair costs O(N² · R), so reducing each listing to two scalars is the key improvement.
from typing import Dict, List
def find_handoff_pairs(listings: Dict[str, List[int]], s: int, e: int) -> List[List[str]]:
if s >= e or not listings:
return []
names = sorted(listings)
prefix_end = {} # name -> last day of consecutive run from s (or None)
suffix_start = {} # name -> first day of consecutive run back from e (or None)
for name in names:
days = set(listings[name])
# Compute how far a consecutive run starting at s can reach
if s not in days:
prefix_end[name] = None
else:
day = s
while day <= e and day in days:
day += 1
prefix_end[name] = day - 1
# Compute where a consecutive run ending at e starts
if e not in days:
suffix_start[name] = None
else:
day = e
while day >= s and day in days:
day -= 1
suffix_start[name] = day + 1
result = []
for i, first in enumerate(names):
for second in names[i + 1:]:
first_prefix = prefix_end[first]
first_suffix = suffix_start[first]
second_prefix = prefix_end[second]
second_suffix = suffix_start[second]
# first covers [s..t], second covers [t+1..e]
valid_first_then_second = (
first_prefix is not None
and second_suffix is not None
and first_prefix + 1 >= second_suffix
)
# second covers [s..t], first covers [t+1..e]
valid_second_then_first = (
second_prefix is not None
and first_suffix is not None
and second_prefix + 1 >= first_suffix
)
if valid_first_then_second or valid_second_then_first:
result.append([first, second])
return result