int findPlatform(int arr[], int dep[], int n) { sort(arr, arr + n); sort(dep, dep + n); int platform_needed = 1, result = 1; int i = 1, j = 0; while (i < n && j < n) { if (arr[i] <= dep[j]) { platform_needed++; i++; if (platform_needed > result) result = platform_needed; } else { platform_needed--; j++; } } return result; } // Example usage: // arr = {900, 940, 950, 1100, 1500, 1800} // dep = {910, 1200, 1120, 1130, 1900, 2000} // n = 6 // Output: 3
The code sorts arrival and departure times. It then uses two pointers to count how many trains are at the station at the same time. The maximum count is the minimum number of platforms needed.
int arr[] = {1000, 1010, 1025, 1030}; int dep[] = {1020, 1035, 1040, 1050}; int n = 4; int result = findPlatform(arr, dep, n); std::cout << result << std::endl;
Trains overlap between 1010 and 1020 (2 trains), and between 1025 and 1035 (3 trains). Maximum overlap is 3, so output is 3.
Sorting arrival and departure times separately lets us move through events in order, increasing platform count on arrival and decreasing on departure, accurately tracking overlaps.
If arrival time equals departure time, the platform is still needed. Using < instead of <= misses this case, causing wrong platform count.
Sorting arrival and departure times separately and using two pointers is efficient and scalable for large inputs, running in O(n log n) time.
