Room Count and Heaviest Prerequisite Chain for Sessions
Greedy & IntervalsAuto-graded · 18 test casesLast updated
Combine an interval-overlap sweep with a min-heap and a longest weighted path on a DAG using topological order.
You run a venue that hosts a number of sessions. Each session is described by [session_id, start, end]. Some sessions also depend on others: a pair [before_id, after_id] means the session after_id may only begin once before_id has finished.
Your function answers two independent questions and returns both answers together.
Part A: Rooms needed
Find the smallest number of rooms that lets every session run with no two sessions sharing a room at the same moment. A session occupies its room for the half-open span from start up to end. A room that is vacated at time T can be used by another session that starts at exactly T, so back-to-back sessions can share a room.
For this part, only the start and end values matter. Ignore the dependency pairs.
Part B: Heaviest chain
Treat every session as a node whose weight is its length, end - start. Each dependency pair [before_id, after_id] is a directed edge from before_id to after_id. A chain is any path that follows edges, and a single session on its own also counts as a chain. The weight of a chain is the sum of the lengths of the sessions on it.
Return the largest weight over all chains. The actual clock times are not used to order or shift anything here. Only the lengths are added up. With no dependencies, the answer is simply the length of the longest single session.
Output
Return a list of two integers: [min_rooms, heaviest_chain_weight].
If sessions is empty, return [0, 0].
Constraints
0 <= len(sessions) <= 10^4(the empty case returns[0, 0])- Session ids are unique integers.
0 <= start < end <= 10^9- Every id mentioned in
dependenciesbelongs to a session insessions. - The dependency pairs form a directed acyclic graph.
dependenciesmay be empty, and the graph may consist of several disconnected parts.
Examples
Example 1
Input: min_rooms_and_longest_chain([[1, 0, 5], [2, 2, 6], [3, 7, 10]], [[1, 2]])
Output: [2, 9]
Hints
Hint 1
The two questions do not influence each other. Solve each one separately and combine the results at the end.
Hint 2
For the room count, process sessions in order of start time and keep a min-heap of end times for the sessions still running. Remove every end time that is less than or equal to the new start before adding the new one.
Hint 3
For the heaviest chain, compute for each session the heaviest chain that ends at it, handling sessions in topological order (for example Kahn's algorithm). Start each value at the session's own length, and the answer is the maximum over all sessions.
Worked solution
Medium Try it yourself first — then compare your approach, complexity and edge cases.
Approach
The function contains two unrelated sub-problems, so solve each with its standard technique.
Part A: minimum rooms
- Sort the sessions by start time.
- Keep a min-heap of end times for sessions that currently hold a room.
- For each session in start order, pop every end time that is
<= start. Those rooms are free again. The<=is what lets back-to-back sessions share a room. - Push the new session's end time. The heap size is now the number of rooms in use, so track its maximum.
Part B: heaviest chain
- Each session is a node with weight
end - start, and each dependency is an edge. - Let
best[v]be the heaviest chain that ends atv. Thenbest[v] = length[v] + max(best[u])over all prerequisitesuofv, or justlength[v]ifvhas none. - Evaluate this in topological order using Kahn's algorithm. Start with every node of indegree 0. When a node is taken from the queue, relax each outgoing edge with
best[next] = max(best[next], best[cur] + length[next]), lower the indegree ofnext, and enqueue it when it reaches 0. - Every node can be the end of a chain, so the answer is the maximum over all
bestvalues. This covers the no-dependency case and disconnected components automatically.
Why it is correct
Rooms. The number of rooms needed equals the maximum number of sessions overlapping at any instant. That maximum is reached at some session's start. At that moment, after removing finished sessions, the heap holds exactly the sessions that started earlier and are still running, plus the new one. So the largest heap size equals the maximum overlap. This is a lower bound, and reusing freed rooms achieves it.
Chain. Kahn's algorithm dequeues a node only after all of its prerequisites have been processed and have already relaxed their edges into it. Therefore best[v] is final when v is dequeued, which is exactly the recurrence evaluated in a valid order. Because the graph is acyclic, every node is eventually processed.
Complexity
With n sessions and m dependencies:
- Time:
O(n log n + m), from the sort and heap operations plus a linear pass over the graph. - Space:
O(n + m).
Reference solution
import heapq
from collections import deque
from typing import List
def min_rooms_and_longest_chain(sessions: List[List[int]], dependencies: List[List[int]]) -> List[int]:
if not sessions:
return [0, 0]
# Part A: sweep by start time, heap holds end times of running sessions
by_start = sorted(sessions, key=lambda s: s[1])
running_ends = []
rooms = 0
for _, start, end in by_start:
while running_ends and running_ends[0] <= start:
heapq.heappop(running_ends)
heapq.heappush(running_ends, end)
rooms = max(rooms, len(running_ends))
# Part B: longest weighted path in a DAG via Kahn's algorithm
length = {sid: end - start for sid, start, end in sessions}
successors = {sid: [] for sid in length}
indegree = {sid: 0 for sid in length}
for before_id, after_id in dependencies:
successors[before_id].append(after_id)
indegree[after_id] += 1
best_ending_here = dict(length)
queue = deque(sid for sid in length if indegree[sid] == 0)
while queue:
cur = queue.popleft()
for nxt in successors[cur]:
candidate = best_ending_here[cur] + length[nxt]
if candidate > best_ending_here[nxt]:
best_ending_here[nxt] = candidate
indegree[nxt] -= 1
if indegree[nxt] == 0:
queue.append(nxt)
return [rooms, max(best_ending_here.values())]