Nearest Eligible Elevator
Learn this problemProblem statement
You are given two parallel arrays describing a group of elevators:
floors[i]is the current floor of elevatori.states[i]is"UP","DOWN", or"IDLE".
A passenger is waiting at passengerFloor and wants to travel in passengerDirection, which is either "UP" or "DOWN".
An elevator is eligible under these rules:
- An idle elevator can serve any passenger.
- An elevator moving up can serve the passenger only when the passenger also wants to go up and the elevator is at or below
passengerFloor. - An elevator moving down can serve the passenger only when the passenger also wants to go down and the elevator is at or above
passengerFloor.
Return the index of the eligible elevator with the smallest absolute floor distance from the passenger. For this exercise, assume equally distant eligible elevators are ordered by their smaller original index. If no elevator is eligible, return -1.
Function
nearestEligibleElevator(floors: int[], states: String[], passengerFloor: int, passengerDirection: String) → intExamples
Example 1
floors = [2,8,12]states = ["UP","IDLE","DOWN"]passengerFloor = 6passengerDirection = "UP"return = 1Elevator 0 is moving up toward the passenger and is 4 floors away. Elevator 1 is idle and is 2 floors away. Elevator 2 is moving in the opposite direction. Therefore, elevator 1 is the nearest eligible elevator.
Example 2
floors = [3,9,9,15]states = ["UP","DOWN","IDLE","DOWN"]passengerFloor = 9passengerDirection = "UP"return = 2Elevator 1 is already at floor 9, but it is moving down while the passenger wants to go up, so it is ineligible. Elevator 2 is idle at the passenger's floor and is selected.
Example 3
floors = [3,7,12]states = ["IDLE","IDLE","UP"]passengerFloor = 5passengerDirection = "UP"return = 0Elevators 0 and 1 are both idle and both are 2 floors away. The smaller-index tie rule selects elevator 0.
Example 4
floors = [8,2]states = ["UP","DOWN"]passengerFloor = 5passengerDirection = "DOWN"return = -1Elevator 0 is moving in the wrong direction. Elevator 1 is moving down from below the passenger, so the passenger is not along its current path. No elevator is eligible.
Constraints
floors.length == states.length- Each value in
statesis"UP","DOWN", or"IDLE". passengerDirectionis"UP"or"DOWN".- Every floor is a 32-bit signed integer.
More Pinterest problems
- Nested Set Structural EquivalencePHONE SCREEN · ONSITE INTERVIEW · Seen Jul 2026
- Time-Ordered Elevator DispatchPHONE SCREEN · Seen Jul 2026
- Assign Pins to the Shortest ColumnPHONE SCREEN · Seen May 2026
- Minimize Expression with ParenthesesOA · Seen Feb 2026
- Bubble ExplosionOA · Seen Feb 2026
- Travel Distance on ScootersOA · Seen Feb 2026
- Join Sources with Lagged Destination TimestampsONSITE INTERVIEW · Seen Aug 2024