FunctionRacerProblemsRace

Shunting Through the Siding

EasyStacks and queuesPython, JavaScript, TypeScript, Java, C++

Train cars numbered 1 to n arrive on a track in increasing order, where n = len(order). Beside the track is a dead-end siding: the next arriving car can be moved into it, and only the car that went in last can come out. Every car passes through the siding.

Return True if the cars can come out of the siding in exactly the order order, and False otherwise. An empty order gives True.

Example 1

order [3,1,2]
returns false

Car 3 comes out first, so cars 1 and 2 are already in the siding with 2 on top, and car 1 cannot come out next.

Example 2

order [2,3,1]
returns true

Move in 1 and 2, take out 2, move in 3, take out 3, then take out 1.

Constraints

Race itor take your time

Write it in your browser, against the clock. The model solution, stepped through line by line, comes after.

More Stacks and queues problems