FastPrepPark Train Cars by Preference

Park Train Cars by Preference

Mercor logoMercor● MediumFULLTIMEONSITE INTERVIEW
Learn

Problem statement

A rail yard has parking spots numbered from 0 through spotCount - 1. Train car i may be parked in any spot listed in preferences[i].

Each spot may hold at most one car. Return whether every train car can be assigned to an acceptable spot. Cars may be reassigned from an earlier choice while searching for a complete placement.

Function

canParkTrain(spotCount: int, preferences: int[][]) → boolean

Examples

Example 1

spotCount = 3preferences = [[0,1],[1],[1,2]]return = true

The cars can use spots 0, 1, and 2 respectively.

Example 2

spotCount = 2preferences = [[0],[0]]return = false

Both cars require the same single spot, so one remains unparked.

Example 3

spotCount = 4preferences = [[0,1],[0,2],[1,3],[2,3]]return = true

Reassigning an earlier car exposes a complete placement.

Constraints

  • 1 <= preferences.length, spotCount <= 200
  • Each preference list is nonempty and contains distinct valid spot indices.
  • A car occupies exactly one spot and a spot holds at most one car.

More Mercor problems

See Mercor hiring insights
public boolean canParkTrain(int spotCount, int[][] preferences) {
  // write your code here
}
spotCount3
preferences[[0,1],[1],[1,2]]
expectedtrue
Checking account…