×

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.

advent[] = "01:30, 09:50"

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<>();
        pp.add(trains[0].depteTimes);
        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();
            }
            pp.add(curre.depteTime);
        }
        // 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

Related Topics

India Map Pattern in Java

India Map Pattern is the pattern we'll code now using Java, as demonstrated. We will use a star in Java to print our India map.The specialty is that we will only...

4 minutes read.

Pernicious Number in Java

If the number of 1s in a number appearing in the binary representation is the prime number, such a number is known as a pernicious number. A pernicious number always corresponds to...

4 minutes read.

Java Short Keyword

Java supports eight different primitive datatypes. The language has predefined primitive datatypes that are given keyword names. Let's take a closer look at each of the eight primitive data types....

3 minutes read.

Java Import Keyword

Java's import keyword used in the code that follows the import statement, a Java class is declared. Once a Java class is declared, it is possible to use the class...

6 minutes read.

String Matches in Java

Firstly we have to know something about String? Strings are a bundle of different characters that are normally used in Java programming language. Strings are regarded as objects in the Java...

3 minutes read.

How to Calculate Week Number From Current Date in Java?

The WeekFields class's weekOfMonth() method is utilized to return the field for access the week of a month based on this WeekFields. If the first day of the month is a...

3 minutes read.

&amp;&amp; Operator in Java

“ && ” is the conditional - And operator in Java. In Java, it is an example of a logical operator. In Java, the “ & ” operator has two...

3 minutes read.

How to increment and decrement date using Java?

Before understanding how to increment and decrement the date, one must know about the Calendar class in Java. The Java calendar class offers methods for converting dates between a given moment...

3 minutes read.

Compile time vs Runtime in java

Introduction: This article will discuss compile time vs. runtime in java. Compile time and runtime are two programming terms utilized in software improvement. Compile time is when the source code is...

3 minutes read.

Inheritance Program in Java

Inheritance Program in Java Inheritance is one of the important pillars of Object-Oriented Programming that facilitates parent-child relationships in programming. Using inheritance, we can create a new class with the help...

7 minutes read.

Bedrock vs Java

The popularity of Minecraft, a sandbox video game, has skyrocketed. The scope, level of complexity, and variety of gameplay in this game are enormous, and user-generated content has helped to...

4 minutes read.

Camel Case in Java

Java names its classes, interfaces, methods, as well as variables using camel-case syntax. If the name consists of two words, the second word will always begin with a capital letter,...

3 minutes read.

Blocking Queue in Java Example

Let's first briefly comprehend queue before moving on to the topic of "Blocking Queue." A queue seems to be an orderly list of items in which elements are added from...

8 minutes read.

How to get ASCII value of char in Java

Introduction: On this application, you will learn how to find and show the ASCII value of char in Java. That is done with the use of type-casting and also everyday...

4 minutes read.

Exception Handling Program in Java

Exception Handling Program in Java Exception means something that is abnormal. In Java, an exception is treated as a problem that disrupts the normal flow of the program. An exception leads...

7 minutes read.

Collection Programs in Java

Collection Programs in Java Collection in Java provides a way to manipulate or store a group of objects. Each object in a collection is called element. Collection programs in Java mainly...

4 minutes read.

Matrix Multiplication in Java

In Java, using the binary operator (*) we can perform matrix multiplication. A Matrix is a group of arrays. In the multiplication of matrices, the elements of each row are...

3 minutes read.

Java vs DotNET

Before understanding the differences between DotNET and Java, one must know about Java and DotNET. Java Java is a general-purpose programming language that is class-based and object-oriented, with minimal implementation dependencies. Regardless of...

9 minutes read.

Java Externalization

What is Externalization in Java? Externalization is a concept that is advanced to serialization. Serialization is a concept where we can transfer an object from our JVM ( Java virtual machine...

3 minutes read.

Sylvester Sequence in Java

A Sylvester Sequence is a series of numbers in which each term is the sum of the terms before it plus 1. The sequence's first two terms are 2 and...

3 minutes read.