import java.util.*; public class Main { public static int findPlatform(int[] arr, int[] dep) { Arrays.sort(arr); Arrays.sort(dep); int platform_needed = 1, result = 1; int i = 1, j = 0; while (i < arr.length && j < dep.length) { if (arr[i] <= dep[j]) { platform_needed++; i++; } else { platform_needed--; j++; } if (platform_needed > result) result = platform_needed; } return result; } public static void main(String[] args) { int[] arr = {900, 940, 950, 1100, 1500, 1800}; int[] dep = {910, 1200, 1120, 1130, 1900, 2000}; System.out.println(findPlatform(arr, dep)); } }
The code sorts arrival and departure times. It then uses two pointers to count how many trains are at the station simultaneously. The maximum count is the minimum number of platforms needed.
For the given times, the maximum overlap is 3 trains.
The correct approach sorts both arrival and departure times and uses two pointers to track how many trains are at the station at the same time.
while (i < arr.length && j < dep.length) { if (arr[i] < dep[j]) { platform_needed++; i++; } else { platform_needed--; j++; } if (platform_needed > result) result = platform_needed; }
Changing '<=' to '<' causes the code to treat trains arriving exactly at departure time as needing a new platform, which underestimates platforms needed.
int[] arr = {1000, 1010, 1025, 1030}; int[] dep = {1015, 1020, 1035, 1040}; System.out.println(findPlatform(arr, dep)); // findPlatform method same as in c1
The maximum overlap is 3 trains between 1025 and 1030.
Sorting both arrays and using two pointers is efficient and scalable for large inputs, running in O(n log n) time.
