Welcome to our deep dive into the fascinating world of Data Structures and Algorithms! Today, we're going to explore a classic problem known as Minimum Platforms, which is a great introduction to graph theory and dynamic programming.
Imagine a railway station where multiple trains arrive and depart at different times. You are given a list of arrivals and departures for each train. The goal is to find the minimum number of platforms required to accommodate all these trains at the station at any given moment.
Let's break this problem down step by step:
Input: We have a list of trains, where each train is represented by a tuple (arrival_time, departure_time).
Output: We want to find the minimum number of platforms required to accommodate all trains simultaneously.
Constraints: No two trains arrive or depart at the same time.
To solve this problem, we will use a greedy approach combined with a data structure called an Interval List.
An interval list is a data structure used to store a collection of intervals. Each interval is represented as a tuple (start, end), denoting the start and end times of an event.
Now let's implement the Minimum Platforms solution in Python:
def minimum_platforms(trains):
# Sort the trains by arrival time
trains.sort(key=lambda x: x[0])
# Initialize an empty list for intervals
intervals = []
# Iterate through the sorted trains
for train in trains:
# If the current train's interval is not already in the intervals list
if not intervals or intervals[-1][1] < train[0]:
# Add the current train's interval to the intervals list
intervals.append((train[0], train[1]))
else:
# Update the end time of the last interval in the intervals list
intervals[-1][1] = max(intervals[-1][1], train[1])
# Calculate the number of unique intervals
return len(set([interval[0] for interval in intervals]))Explanation:
Let's test our Minimum Platforms solution with an example:
trains = [(900, 940), (910, 950), (930, 1100), (1200, 1500)]
print(minimum_platforms(trains)) # Output: 2In this example, two platforms are required because there are two time slots when multiple trains are present at the station simultaneously (940-950 and 1200-1500).
Question: Given the trains [(900, 940), (910, 950), (930, 1100), (1200, 1500)], how many platforms are required to accommodate all these trains at the station at any given moment?
A: 1 B: 2 C: 3 Correct: B Explanation: Two platforms are required because there are two time slots when multiple trains are present at the station simultaneously (940-950 and 1200-1500).