# Minimum Number of Platforms Required for a Railway Station

The train station problem is one of the most significant problems typically posed in the programming round interview to gauge a candidate's aptitude for logic and problem-solving.

## Problem of Railway Station

The trains' arrival and departure times for a certain railway station are given in this problem. There are two arrays with the names arrival and departure that represent the train's arrival and departure times (on a 24-hour clock). In order for trains to operate on time, we must determine the bare minimum of platforms needed for a station.

Let's use an illustration to better comprehend the issue.

Example:

Input: advent[] = {8:00, 8:30, 8:400, 10:00, 14:30, 17:30}

departs[] = {8:10, 11:00, 12:30, 13:30, 20:00, 21:30}

Output: 3

There are never more than three trains at once (time from 12:00 to 12:30). In order for the railway station to accommodate all the trains, we thus need at least three platforms.

Consider still another instance.

Example 2:

Enter advent[] = "09:10, 01:00" as in Example 2.

The first train in the above-mentioned sequence arrived at 10:20 AM and left at 10:50 AM. There is no assigned train at that station right now. As a result, we just need one platform to distribute the train.

### Alternative to the problem

The following two options are available to determine the absolute minimum the number of platforms necessary:

• The Naive Approach
• The Efficient Approach

### The Naïve Approach

Finding the bare minimum of platforms needed for a railroad station is the easiest method. These 2 nested for loops can be used to obtain the solution.

The inside for loop counts how many intervals cross over the interval represented either by outer for loop. Modify the highest value of a count when the inner loop has finished running. Continue with the successive stage of both the outermost for loop after that. We obtain the highest number of the count whenever the outer loop terminates. It refers to the quantity of platforms necessary at a railroad station.

Because no additional space is utilised, the preceding method has an O(n2) time complexity and an O(1) space complexity.

Algorithm

``````int maxOfOverlaps = 0;
for s = 0 to m-1
int noOfTheOverLaps = 0;
fro h = s+1 to m-1
fy train[s] OVERLAPS WITH train[h] then
noOfOverLaps++;
iF noOfTheOverLaps > maxOfOverlaps then
maxOfOverlaps = noOftheOverLaps;
return maxOfOverlaps;
``````

Let's include the aforementioned strategy into a Java program.

PlatformDemo.java

``````import java.util.*;
public class PlatformDemo
{
// function to determine the least amount of platforms necessary for a railroad station
static int findThePlatforms(int m, int arriv[],int departs[])
{
int rest=1;
for(int s=0; s<=n-1; s++)   // This is the outer for loop
{
// overlapping interval count for just this iteration
int coun=1;
for(int j=s+1; h<=n-1; h++) //This is the inner for loop
{
//&& returns the result as true if any of the two conditions is true
// || returns the result if any one of the conditions does.
if((arriv[s]>=arriv[h] && arriva[s]<=departs[h]) || (arriv[h]>=arriv[s] && arriv[h]<=departs[s]))
{
// when any of the conditions are met, increases its count variable by one.
coun++;
}
}
// determining the highest value & updating the outcome
rest = Math.max(rest, coun);
}
return rest;
}
public static void main (String args[])
{
// setting up its arrival and departure times in an array from scratch
int[] arriv = {920, 950, 960, 1110, 1550, 1850};
int[] departs = {930, 1250, 1135, 1155, 1950, 2100};
// determines the arrival time array's length.
int m=arriv.len;
//Here occurs the function calling
int overallCoun = findThePlatforms(m, arriv, departs);
// displays the outcome on the console
System.out.println("Minimum necessary number of platforms: "+overallCoun);
}
}
``````

Output:

`Minimum necessary number of platforms: 3`

## The efficient approach

Both the arrival timing and departure timing arrays will first be sorted. The counting logic makes it simple to determine how many trains has arrived at the station but have not yet left.

How many platforms are needed in total at any given time is the question. By calculating the difference between the arrival and departure times at that time, we may figure out the complete number of platforms. The ultimate solution will be the value among all periods that we determined above. The following programme has the following two prerequisites, which we have verified:

• If (arriv[s]=departs[h]) then an additional platform was needed. Increase both the count and s because we have an additional platform.
•  if (arriv[s]>departs[h]). We have to make room on that platform for the other trains that are coming. To accomplish the same, we increase the variable j while decreasing the variable count. Update the result using the maximum number of iterations in the while loop (result, count).

In the method described above, we utilised sorting to arrange the trains' arrival and departure times, which took O(logn) time. We must also traverse the array, which takes O(n) time. Consequently, O is the entire temporal complexity O(nlogn). The method uses no more space, hence O(1) is the space complexity.

RailwayStationDemo.java

``````import java.util.Array;
public class RailwayStationDemo
{
// function to determine the least amount of platforms necessary for a railroad station
static int findThePlatform(int arriv[], int departs[], int m)
{
// simply using the Array, you may order arrival and departure function Array.sort()
Array.sort(arriv);
Array.sort(departs);
// The need form shows how many platforms are needed at any given time
int requipaltforms = 1, ans = 1;
int s = 1, h = 0;
// Similar to merging, merge sort processes every event in chronological order.
while (s < m && h < m)
{
// If arrival is the following event in the sorted order, increase the requiplatforms variable.
if (arriv[s] < departs[h])
{
requipaltforms++;
s++;
// If (requipaltforms > ans), update the ans if necessary.
ans = requipaltforms;
}
// otherwise, the number of platforms must be decreased.
else
{
requipaltforms--;
h++;
}
}
return ans;
}
//It is the driver code
public static void main(String args[])
{
// setting the beginning values of an array's arrival and departure times
int arriv[] = {920, 955, 960, 1120, 1530, 1900};
int departs[] = {930, 1220, 1130, 1240, 1800, 1930};
// determines the arrival time array's length.
int m = arriv.len;
//Here occurs the function calling
System.out.println("Minimum Number of Platforms Required = "+ findThePlatform(arriv, departs, m));
}
}
``````

Output:

`Minimum Number of Platforms Required = 1`

We note that the highest train numbers that can be present at any given moment here on train station equals equal to the minimum amount of platforms required on the railway station.

summary

The programme execution complexity for the naive technique is O(n2) while the time complexity again for efficient approach. The naive approach is significantly more complexity O(nlogn).

## Using The Heap technique

Save the travel times and departure time, arrange data based on arrival time, and then determine whether the following train's arrival time is shorter than the preceding train's departure time. If it is, increase the number of platforms required; otherwise, do not.

Example:

``````import java.io.*;
import java.util.Array;
import java.util.Comparator;
import java.util.PriorityQueue;
class Fun {
private static class TrainTimings {
int arrivTime, deptartTime;
TrainTiming(int arrivTime, int deptartTime)
{
this.arrivTime = arrivTime;
this.depteTime = deptartTime;
}
public String toString()
{
return "(" + this.arrivTime + ","
+ this.depteTime + ")";
}
}
private static class SortByTheArrival
implements Comparator<TrainTiming> {
@Override
public int check(TrainTiming o3,
TrainSchedule o4)
{
return o3.arrivTime – o4.arrivTime;
}
}
// Calculate the bare minimum
// number of platforms needed
public static int countThePlatforms(int[] arr, int[] dept)
{
TrainTimings[] train
= new TrainTimings[arr.len];
// Save the time of arrival and departure.
for (int s = 0; s < arr.len; s++) {
train[s] = new TrainTimings(arr[s], dept[s]);
}
// Organize trains according to arrival time
Array.sort(train, new SortByTheArrival());
PriorityQueue<Integer> pp = new PriorityQueue<>();
int coun = 1;
for (int s = 1; s < arr.len; s++) {
TrainTiming current = train[s];
// Verify that the current train's
// arrival time is lower than or equal
// to the prior train's departure time.
if (curre.arrivTimes <= pp.peek()) {
coun++;
}
else {
pp.polls();
}
}
// give the total number of platforms that are necessary.
return count;
}
public static void main(String[] args)
{
int[] arr = { 910, 945, 955, 1110, 1550, 1900 };
int[] dep = { 920, 1250, 1125, 1135, 1950, 2100 };
int rest = countThePlatforms(arr, dept);
System.out.println(rest);
}
}
``````

Output:

`3`