×

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

Java Integer doubleValue() method

The doubleValue() method of Integer class returns a double value for this Integer after a widening primitive conversion. Syntax public double doubleValue() Parameters NA Specified by This method is specified by doubleValue in class Number Return Value This...

1 minute read.

Java Enum vs Class

Enumerations are used in programming languages to represent collections of named constants. For instance, the four suits in a deck of playing cards might represent four integrators named Club, Diamond,...

7 minutes read.

Java LinkedList vs ArrayList

LinkedList In LinkedList, each element is a distinct entity containing an information portion and an address component, and the elements are not kept in consecutive locations. Pointers & addresses are used...

3 minutes read.

Difference between JIT and JVM in Java

In this tutorial, we will discuss the difference between JIT (Just In Time Compiler) and JVM (Java Virtual Machine) in Java. Before we move to the differences, let's understand what...

4 minutes read.

How to Create a Generic List in Java?

Generics are types that have parameters. The goal is to make it possible for methods, classes, and interfaces to take type (Integer, String, etc., and user-defined types) as a parameter....

4 minutes read.

How to create a linked list in Java

Introduction: The linked listing is one type of linear statistics shaped like an array. Not like arrays, linked listing factors aren't stored in a contiguous place. The elements have linked...

3 minutes read.

Diffie Hellman Algorithm in Java

In this section, you will be acknowledged about Diffie Hellman algorithm clearly step wise along with an example and also an example program. Diffie Hellman Algorithm One of the most significant algorithms...

3 minutes read.

Java float vs double

Java : Java is a pure object oriented language. It was introduced by James Gosling in the year 1995. The first public implementation of java was done by sun micro systems...

7 minutes read.

Java String replaceFirst() method

This method replace the first substring with user specified String. Syntax: public String replaceFirst(String Regexp, String Replacement) Parameter: Regexp : Regular Expression Replacement : the String which would replace found expression Return: a string Java String replaceFirst()...

1 minute read.

Process and Thread in Java

Process It is a program that is running on your computer. The process is a heavy-weight, which takes memory separately to other processes. The process may be a small background task like spell-checker; it...

11 minutes read.

Types of Sockets in Java

The fundamental idea behind Java's networking capability is the socket. Early in the 1980s, the Berkeley UNIX 4.2BSD version included the socket paradigm. Berkeley socket is the term employed as...

9 minutes read.

Java try catch

Java try catch There can be statements that can cause exceptions, and the exception leads to abnormal termination of the program. To avoid that abnormal termination, those statements that look potent...

4 minutes read.

Java SHA256

Definition: In cryptography, SHA is a hash function that takes 20 bytes of input and produces an approximate 40-digit hexadecimal integer as the hash result. Class for Message Digest: Java's MessageDigest Class,...

2 minutes read.

Java delete directory

The File classes in Java may symbolize a directory or a file on the system. Inside the java.io package, the Files class is accessible. The File class has several helpful...

2 minutes read.

Structure of Java Program

Java is well-known as an object-oriented, secure, and platform-independent programming language. The Java programming language allows us to construct a wide variety of programs. Therefore, it is essential to fully...

6 minutes read.

Java Custom Exception

Java Custom Exception Java language facilitates us to create our own exceptions. The class intended to throw the Custom Exception has to be derived from the Java Exceptionor RuntimeExceptionclass. The Java...

4 minutes read.

Tetranacci Number in Java

This article mainly describes tetranacci number identification and the Java Program for Tetranacci numbers. Tetranacci number Tetranacci numbers and Fibonacci numbers are related. The key contrast is that a Tetranacci number depends...

3 minutes read.

Java Command Line Arguments

Java command line arguments Command line argument is an input or argument to the program when you run the program. In Java, we can take the inputs from the console, and...

2 minutes read.

Java Output Formatting

Sometimes we want a program's output to be displayed in a specific format. The printf () function in the C programming language can be used to achieve this. We will...

4 minutes read.

How annotations work in Java

Annotations were introduced by sun microsystem and are available from the java 1.5 version. In general, configurations can be done either by XML or by annotations. Hibernate and spring framework users prefer...

4 minutes read.