Find vehicles ahead (Former Contest Question)

It’s a former contest question. I want the answer to be below nlog(n).
It would be really appreciated if you could share the code with the approach.