KatInterview

Room Count and Heaviest Prerequisite Chain for Sessions

Greedy & IntervalsAuto-graded · 18 test cases
MediumAuto-gradedGreedy & Intervalsintervalsmin-heaptopological-sort

Last 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 dependencies belongs to a session in sessions.
  • The dependency pairs form a directed acyclic graph. dependencies may 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.