Semester Planner Plus Burst-Limited Request Filter
Trees & GraphsAuto-graded · 26 test casesLast updated
Combine topological ordering to find the minimum number of semesters (or detect a cycle) with a deque-based simulation of a two-rule request throttle that reports dropped timestamps.
Implement one function that answers two independent questions and returns the results together in a dictionary.
Part 1: Semester planning
There are n courses numbered 0 through n - 1. Each entry [a, b] in prerequisites means course b must be finished in a semester strictly before the semester in which course a is taken.
- Every course takes exactly one semester.
- You may take any number of courses in one semester, provided all of their prerequisites were completed in earlier semesters.
Determine:
- whether all courses can be completed at all (this fails if the prerequisites contain a cycle, including a course that requires itself), and
- the smallest number of semesters needed to complete every course. If completing all courses is impossible, this value is
-1.
Part 2: Throttled request log
You are given requests, a non-decreasing list of arrival times in whole seconds. The index of an entry is the request's ID, and the value is its arrival time. Several requests may share the same time.
A throttle examines requests one at a time in index order. A request is dropped if accepting it would break either rule below. Otherwise it is accepted.
- At most 3 accepted requests may have the same arrival time
t. - For a request at time
t, at most 20 accepted requests may have arrival times in the inclusive range[t - 9, t], counting the request itself.
Only accepted requests count toward either rule. A dropped request has no effect on later decisions.
Collect the arrival times of all dropped requests, in the order they appear in requests.
Return value
Return a dictionary with exactly these keys:
"can_finish":Trueif all courses can be completed, otherwiseFalse."min_semesters": the minimum number of semesters, or-1ifcan_finishisFalse."dropped_requests": the list of arrival times of dropped requests, in input order.
Constraints
1 <= n <= 10^50 <= len(prerequisites) <= 2 * 10^5- Each prerequisite pair has two course indices in
[0, n - 1]. Duplicate pairs and self-pairs may appear. 1 <= len(requests) <= 10^50 <= requests[i] <= 10^9requestsis sorted in non-decreasing order.
Examples
Example 1
Input: plan_semesters_and_filter_requests(2, [[1, 0]], [1, 1, 1, 1, 2])
Output: {'can_finish': True, 'min_semesters': 2, 'dropped_requests': [1]}
Example 2
Input: plan_semesters_and_filter_requests(4, [[1, 0], [2, 1], [3, 2]], [0, 0, 0, 0, 1, 2, 3])
Output: {'can_finish': True, 'min_semesters': 4, 'dropped_requests': [0]}
Example 3
Input: plan_semesters_and_filter_requests(3, [[0, 1], [1, 2], [2, 0]], [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0])
Output: {'can_finish': False, 'min_semesters': -1, 'dropped_requests': [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0]}
Hints
Hint 1
Treat each pair [a, b] as a directed edge b -> a. Courses with no unmet prerequisites can be taken right away; repeatedly remove them and update their dependents (Kahn's algorithm).
Hint 2
While removing courses, track for each course the earliest semester it can be taken: one more than the largest semester among its prerequisites. If fewer than n courses are ever removed, a cycle exists.
Hint 3
For the throttle, keep a deque of accepted timestamps and a per-second count of accepted requests. Before each decision, pop timestamps older than t - 9 from the front, then check the two limits (3 at this second, 20 in the window).
Worked solution
Hard Try it yourself first — then compare your approach, complexity and edge cases.
Part 1: Semester planning
Approach. Turn each pair [a, b] into a directed edge b -> a. Run Kahn's algorithm (BFS topological sort):
- Compute every course's in-degree and enqueue all courses with in-degree 0. They can be taken in semester 1.
- Pop a course
u, count it as completed, and for each dependentvsetsemester[v] = max(semester[v], semester[u] + 1). Decrementv's in-degree and enqueue it when it reaches 0. - If all
ncourses were popped, the graph is acyclic and the answer is the largestsemestervalue. Otherwise returncan_finish = Falseandmin_semesters = -1.
Why it is correct. A course on a cycle always has an unprocessed predecessor on that cycle, so its in-degree never hits 0 and it is never popped. In an acyclic graph there is always an unprocessed node with in-degree 0, so everything is eventually popped. Since there is no limit on courses per semester, each course should be taken as early as possible, which is one semester after its latest prerequisite. When a node is enqueued, all its predecessors have been processed, so its value is final. The answer is therefore the length (in nodes) of the longest prerequisite chain. Self-pairs and cycles leave nodes unprocessed. Duplicate pairs add and remove in-degree equally, so they are harmless.
Part 2: Throttled request log
Approach. Because times are non-decreasing, keep:
- a deque of accepted timestamps still inside the window
[t - 9, t], and - a dictionary counting accepted requests per timestamp in the window.
For each request at time t, first pop from the front any timestamp < t - 9, adjusting the counts. Then drop the request if the count at t is already 3 or the deque already holds 20 entries. Otherwise accept it by appending t and incrementing its count.
Why it is correct. Only accepted requests are stored, matching the rule that dropped requests are ignored. Time never goes backward, so an evicted timestamp can never re-enter a later window. After eviction, the deque length is exactly the number of accepted requests in [t - 9, t], and the dictionary count at t is exactly the number accepted at that second. Checking those two numbers is equivalent to the two rules.
Complexity
- Part 1: time O(n + E), space O(n + E), where E is the number of prerequisite pairs.
- Part 2: time O(m) amortized for m requests, since each accepted timestamp is added and removed at most once. Working space is O(1) because the deque holds at most 20 entries, plus O(m) for the output.
Reference solution
from collections import deque
from typing import List, Dict
def plan_semesters_and_filter_requests(n: int, prerequisites: List[List[int]], requests: List[int]) -> Dict[str, object]:
# Part 1: Kahn's algorithm with longest-path tracking.
graph = [[] for _ in range(n)]
indegree = [0] * n
for course, prereq in prerequisites:
graph[prereq].append(course)
indegree[course] += 1
queue = deque()
semester = [1] * n
for c in range(n):
if indegree[c] == 0:
queue.append(c)
completed = 0
best = 0
while queue:
u = queue.popleft()
completed += 1
if semester[u] > best:
best = semester[u]
for v in graph[u]:
if semester[u] + 1 > semester[v]:
semester[v] = semester[u] + 1
indegree[v] -= 1
if indegree[v] == 0:
queue.append(v)
can_finish = completed == n
if not can_finish:
best = -1
# Part 2: simulate the throttle using only accepted requests.
window = deque()
per_second = {}
dropped = []
for t in requests:
while window and window[0] < t - 9:
old = window.popleft()
per_second[old] -= 1
if per_second[old] == 0:
del per_second[old]
if per_second.get(t, 0) >= 3 or len(window) >= 20:
dropped.append(t)
else:
window.append(t)
per_second[t] = per_second.get(t, 0) + 1
return {
"can_finish": can_finish,
"min_semesters": best,
"dropped_requests": dropped,
}