After processing all events, we return max_platforms, which is 3.
💡 This value represents the minimum number of platforms required to avoid conflicts.
Line:return max_platforms
💡 The maximum platforms needed at any time is the answer to the problem.
def min_platforms_sweep_line(arrivals, departures):
events = []
# STEP 1: Create arrival events
for time in arrivals:
events.append((time, 1)) # arrival
# STEP 2: Create departure events
for time in departures:
events.append((time, -1)) # departure
# STEP 3: Sort events by time and type
events.sort(key=lambda x: (x[0], x[1]))
# STEP 4: Initialize counters
platforms_needed = max_platforms = 0
# STEP 5-16: Process each event
for i, (_, event_type) in enumerate(events):
platforms_needed += event_type # STEP i+5
max_platforms = max(max_platforms, platforms_needed)
# STEP 17: Return result
return max_platforms
if __name__ == '__main__':
arrivals = [900, 940, 950, 1100, 1500, 1800]
departures = [910, 1200, 1120, 1130, 1900, 2000]
print(min_platforms_sweep_line(arrivals, departures)) # Output: 3
📊
Minimum Number of Platforms Required - Watch the Algorithm Execute, Step by Step
Watching the algorithm process each event one by one reveals how overlapping intervals cause platform requirements to increase and decrease, making the concept of sweep line intuitive.
✓ Sorting events by time and prioritizing departures before arrivals at the same time is crucial.
This prevents overcounting platforms when trains arrive and depart simultaneously, which is not obvious from code alone.
✓ The sweep line approach converts interval overlap into a simple running count problem.
Visualizing events as points on a timeline helps understand how overlaps translate to platform needs.
✓ Tracking both current platforms needed and maximum platforms needed separately is essential.
The maximum platforms needed is the final answer, but the current count fluctuates as events are processed.
Practice
(1/5)
1. Consider the following Python function for interval intersections:
from typing import List
def intervalIntersection(A: List[List[int]], B: List[List[int]]) -> List[List[int]]:
i, j = 0, 0
result = []
while i < len(A) and j < len(B):
if A[i][1] < B[j][0]:
i += 1
elif B[j][1] < A[i][0]:
j += 1
else:
start = max(A[i][0], B[j][0])
end = min(A[i][1], B[j][1])
result.append([start, end])
if A[i][1] < B[j][1]:
i += 1
else:
j += 1
return result
A = [[0,2],[5,10],[13,23],[24,25]]
B = [[1,5],[8,12],[15,24],[25,26]]
print(intervalIntersection(A, B))
What is the final output printed by this code?
easy
A. [[1,2],[5,5],[8,10],[15,23],[24,25],[25,26]]
B. [[1,2],[5,5],[8,10],[15,23],[24,25],[25,25]]
C. [[1,2],[5,5],[8,10],[15,23],[24,24],[25,26]]
D. [[1,2],[5,5],[8,10],[15,23],[24,24],[25,25]]
Solution
Step 1: Trace first intersection
Compare [0,2] and [1,5]: overlap is [1,2], add to result.
Step 2: Advance pointers and find all intersections
Following pointer moves and overlaps yield [[1,2],[5,5],[8,10],[15,23],[24,24],[25,25]].
Hint: Trace pointer increments carefully to avoid off-by-one errors [OK]
Common Mistakes:
Including intervals beyond intersection
Merging adjacent but non-overlapping intervals
Off-by-one in pointer increments
2. What is the time complexity of the optimal car pooling solution using the difference array and prefix sum approach, given n trips and maximum location L?
medium
A. O(n * L) because we must simulate passenger count at every location for each trip
B. O(n + L) because we process each trip once and then sweep through the difference array once
C. O(n log n) due to sorting trips by start location before processing
D. O(L) because the difference array size dominates and trips are processed in constant time
Solution
Step 1: Analyze trip processing
Each of the n trips updates two positions in the difference array -> O(n)
Step 2: Analyze prefix sum sweep
We iterate over the difference array of size L once -> O(L)
Final Answer:
Option B -> Option B
Quick Check:
Sum of O(n) + O(L) operations [OK]
Hint: Difference array updates O(n), prefix sum O(L) [OK]
Common Mistakes:
Confusing brute force O(n*L) with optimal
Assuming sorting is required
Ignoring prefix sum sweep cost
3. What is the time complexity of the optimal sweep line algorithm for Employee Free Time, given N total intervals across all employees?
medium
A. O(N log N) due to sorting all interval endpoints
B. O(N log M) where M is number of employees
C. O(N) because each interval is processed once
D. O(N²) due to nested iteration over intervals
Solution
Step 1: Identify main operations
We create 2N events (start and end per interval) and sort them.
Step 2: Sorting events dominates complexity
Sorting 2N events takes O(N log N). The sweep through events is O(N).
Final Answer:
Option A -> Option A
Quick Check:
Sorting dominates, so O(N log N) [OK]
Hint: Sorting interval endpoints dominates time complexity [OK]
Common Mistakes:
Assuming linear time because each interval processed once
4. The following code attempts to determine if a person can attend all meetings. Identify the line containing the subtle bug that causes incorrect results for intervals that just touch (e.g., [1,5] and [5,10]).
from typing import List
def can_attend_meetings(intervals: List[List[int]]) -> bool:
intervals.sort(key=lambda x: x[0])
end = float('-inf')
for interval in intervals:
if interval[0] <= end:
return False
end = interval[1]
return True
medium
A. Line 6: if interval[0] <= end:
B. Line 3: intervals.sort(key=lambda x: x[0])
C. Line 5: for interval in intervals:
D. Line 7: end = interval[1]
Solution
Step 1: Understand the overlap condition
Meetings that just touch (e.g., end=5 and start=5) should not be considered overlapping.
Step 2: Identify the bug
The condition uses <= which incorrectly treats touching intervals as overlapping. It should use < instead.
Final Answer:
Option A -> Option A
Quick Check:
Changing <= to < fixes false positives on touching intervals [OK]
Hint: Overlap check must use <, not <= [OK]
Common Mistakes:
Using <= causes false overlap detection on touching intervals
5. Examine the following buggy code for the Meeting Rooms II problem. Which line contains the subtle bug that can cause incorrect room count?
medium
A. Line 3: Missing check for empty intervals list.
B. Line 9: Incorrect condition using >= instead of > for overlap.
C. Line 11: Using heappush without popping first.
D. Line 6: Intervals are not sorted before processing.
Solution
Step 1: Identify missing sorting.
Intervals must be sorted by start time before heap processing; missing this breaks heap logic.
Step 2: Confirm other lines.
Empty check is present; condition >= is correct for allowing room reuse; pushing after popping is correct.
Final Answer:
Option D -> Option D
Quick Check:
Without sorting, heap logic fails to track earliest ending meeting [OK]
Hint: Heap logic requires sorted intervals by start time [OK]