Given arrival and departure times of trains at a railway station, find the minimum number of platforms required so that no train waits. Each platform holds one train at a time.
[900, 940, 950, 1100, 1500, 1800][910, 1200, 1120, 1130, 1900, 2000]3[900, 1100, 1235][1000, 1200, 1240]1arr[] and dep[] independentlyi=1, j=0, plat=1, ans=1 — first train always needs a platformarr[i] ≤ dep[j] → arrival first → plat++, i++arr[i] > dep[j] → departure first → plat--, j++ans = max(ans, plat) after every eventSorting both arrays and sweeping them with two pointers simulates processing events in chronological order. When an arrival comes before the next departure, a platform must be acquired. When a departure comes first, one is freed. The peak simultaneous count is the answer — we never need more platforms than the most trains present at once.
Checking how many trains overlap each train is O(n²). We only care about the moments when trains come and go.
Sort the arrival times and the departure times separately. Sweep through time with two pointers, and at each step take whichever event comes first. An arrival adds a platform and a departure frees one, so track the maximum in use.
Sort the events and sweep the timeline. The answer is the peak number of trains at the same time.
Run the animation above on your own input, or watch the 1:26 video explanation of Minimum Platforms with a dry run and Java code.