Since the 2 trains are running towards each other, then their combined speed is:
62 + 40 = 102 km/h
Convert 102 km/h to meters per second =28 1/3 m/s
Since they passed each other in 18 seconds, then:
28 1/3 m/s x 18 seconds =510 meters - The length of the 2nd (longer) train.
Just to confirm the above, the 250 m train would have covered its length in:
250 / (28 1/3 m/s) =8.824 seconds. And 18 seconds - 8.824 seconds =9.176 seconds that would have taken the longer train to pass. So:9.176 seconds x 28 1/3 m/s =260 extra meters covered by the longer train.
So, 260 m + 250 m = 510 meters - the length of the 2nd train.