BNSF Railway interview question

It was a medium LC problem