Find the Meeting Slot That Conflicts With the Most Others
SQL & DataModel answerLast updated
Given a table of time-bounded sessions, write SQL to find which session overlaps the largest number of other sessions and report that count.
Setup
You have a bookings table that logs scheduled sessions, each with a unique ID and a start and end timestamp.
bookings
| booking_id | start_time | end_time |
|------------|---------------------|---------------------|
| 1 | 2023-01-01 09:00:00 | 2023-01-01 10:00:00 |
| 2 | 2023-01-01 09:30:00 | 2023-01-01 11:00:00 |
| 3 | 2023-01-01 10:30:00 | 2023-01-01 12:00:00 |
| 4 | 2023-01-01 13:00:00 | 2023-01-01 14:00:00 |
Task
Write a SQL query that returns the booking_id that conflicts (overlaps in time) with the greatest number of other bookings, along with that conflict count.
Two bookings conflict if their time ranges overlap at all. Treat intervals as half-open — if one booking ends exactly when another begins, they do not conflict.
If multiple bookings share the highest conflict count, return all of them.
Expected Output
| booking_id | overlap_count |
|------------|---------------|
| 2 | 2 |
What the interviewer expects
- A correct two-interval overlap predicate, with a brief justification
- Proper self-exclusion so a booking isn't counted as conflicting with itself
- Handling of bookings with zero conflicts
- A comment on ties and how your query handles them
- (Bonus) A note on how the approach scales and what you'd do for a very large table
Hints
Hint 1
Two intervals do NOT overlap when one ends before or exactly when the other starts. Negate that condition to get the overlap predicate: start_a < end_b AND end_a > start_b.
Hint 2
Self-join the table so every booking is compared against every other booking, but add a filter to exclude a booking being paired with itself — otherwise every count is inflated by one.
Hint 3
Use a LEFT JOIN (not INNER JOIN) so bookings with zero conflicts still appear in the output with a count of 0. Pair this with COUNT(b.booking_id) rather than COUNT(*), or the NULL-padded row from the left join gets counted as 1.
Model answer
Medium Try it yourself first — then compare your approach, complexity and edge cases.
Core Idea: The Overlap Predicate
The cleanest way to reason about whether two intervals overlap is to think about when they don't. Two bookings A and B have no conflict when A ends at or before B starts (end_a <= start_b) or B ends at or before A starts (end_b <= start_a). Negate that and you get the single compound condition that catches every overlapping shape:
start_a < end_b AND end_a > start_b
This handles partial overlaps from either side, one interval fully containing the other, and identical intervals — all in one line.
Walkthrough on the Sample
| Pair | Overlap? | Reason |
|---|---|---|
| 1 & 2 | Yes | 09:00–10:00 and 09:30–11:00 share 09:30–10:00 |
| 1 & 3 | No | booking 1 ends at 10:00, booking 3 starts at 10:30 |
| 2 & 3 | Yes | 09:30–11:00 and 10:30–12:00 share 10:30–11:00 |
| 1/2/3 & 4 | No | booking 4 is entirely after the others |
Conflict counts: booking 1 → 1, booking 2 → 2, booking 3 → 1, booking 4 → 0.
SQL Solution
WITH conflict_counts AS (
SELECT
a.booking_id,
COUNT(b.booking_id) AS overlap_count -- NULL from LEFT JOIN not counted
FROM bookings a
LEFT JOIN bookings b
ON a.booking_id <> b.booking_id -- exclude self-match
AND a.start_time < b.end_time -- overlap predicate
AND a.end_time > b.start_time
GROUP BY a.booking_id
),
ranked AS (
SELECT
booking_id,
overlap_count,
RANK() OVER (ORDER BY overlap_count DESC) AS rnk
FROM conflict_counts
)
SELECT booking_id, overlap_count
FROM ranked
WHERE rnk = 1
ORDER BY booking_id;
If the interviewer wants exactly one row with a deterministic tie-break, swap out the ranked CTE:
SELECT booking_id, overlap_count
FROM conflict_counts
ORDER BY overlap_count DESC, booking_id ASC
LIMIT 1;
State which version you're using and why — "I'm returning all ties via RANK() because silently dropping tied results is usually wrong unless the caller asks for it."
Why Each Detail Matters
LEFT JOIN + COUNT(b.booking_id) instead of INNER JOIN or COUNT(*)
An INNER JOIN drops bookings with zero conflicts entirely. A LEFT JOIN keeps them, but the unmatched right side is NULL. Using COUNT(b.booking_id) skips those NULLs and correctly produces 0. Using COUNT(*) would return 1 for every non-overlapping booking — a subtle bug that interviewers specifically watch for.
Self-exclusion with a.booking_id <> b.booking_id
Every interval trivially satisfies the overlap predicate against itself. Without this filter, every count is one too high.
RANK() vs ROW_NUMBER()
ROW_NUMBER() assigns a unique rank and will arbitrarily drop a tied session. RANK() gives the same rank to all tied rows, which is almost always the right behaviour here.
Edge Cases Worth Raising
- Touching endpoints. The strict
<and>predicate treatsend_a = start_bas non-overlapping (half-open intervals). If the business defines "touching" as a conflict, switch to<=/>=. Clarify this upfront. - NULL
end_time(an open-ended or still-active session). The comparison with NULL yields NULL, silently excluding that booking from all join matches. Fix withCOALESCE(end_time, CURRENT_TIMESTAMP)or a sentinel far-future date. - Invalid rows where
end_time <= start_time. These match nothing under strict inequality and are effectively invisible. Filter them out with aWHEREclause or raise them as a data-quality issue. - Ties. Always ask whether the caller wants all tied results or just one. Default to returning all of them.
Complexity and Scaling
The self-join is O(n²) — every booking is compared with every other booking. For an interview table that's fine. At millions of rows, you'd want an index on (start_time, end_time) to enable range scans, or you'd reframe the problem using a subtraction approach:
For each booking i, the number of non-conflicting bookings is the count of bookings that end entirely before i starts plus those that start entirely after i ends. With sorted arrays and binary search that runs in O(n log n). This is a strong follow-up answer if the interviewer asks "what if this table has 50 million rows?"
Python Solution (O(n log n))
import bisect
import pandas as pd
def max_conflict_booking(bookings: pd.DataFrame) -> pd.DataFrame:
"""Return all booking_ids tied for the most conflicts, with the count.
Intervals are half-open: [start, end). Assumes start_time < end_time."""
if bookings.empty:
return pd.DataFrame(columns=["booking_id", "overlap_count"])
df = bookings.copy()
df["start_time"] = pd.to_datetime(df["start_time"])
df["end_time"] = pd.to_datetime(df["end_time"])
sorted_starts = sorted(df["start_time"])
sorted_ends = sorted(df["end_time"])
n = len(df)
def count_conflicts(row) -> int:
# bookings entirely before this one: their end_time <= this start_time
before = bisect.bisect_right(sorted_ends, row["start_time"])
# bookings entirely after this one: their start_time >= this end_time
after = n - bisect.bisect_left(sorted_starts, row["end_time"])
# subtract self (1) and the two non-overlapping groups
return (n - 1) - before - after
df["overlap_count"] = df.apply(count_conflicts, axis=1)
best = df["overlap_count"].max()
return (
df.loc[df["overlap_count"] == best, ["booking_id", "overlap_count"]]
.sort_values("booking_id")
.reset_index(drop=True)
)
Common Mistakes
- Using
COUNT(*)with aLEFT JOIN— off-by-one for zero-conflict rows. - Forgetting self-exclusion — every count inflated by 1.
- Using
ROW_NUMBER()when ties are possible — silently drops valid results. - Writing four separate overlap cases instead of the two-condition negation — more code, more chances for a logic error.
- Confusing this problem with "maximum concurrency" (the busiest point in time), which is a sweep-line problem and has a different answer.