Problem · Array

Nearest Eligible Elevator

Learn this problem
EasyPinterest logoPinterestFULLTIMEPHONE SCREEN

Problem statement

You are given two parallel arrays describing a group of elevators:

  • floors[i] is the current floor of elevator i.
  • 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) → int

Examples

Example 1

floors = [2,8,12]states = ["UP","IDLE","DOWN"]passengerFloor = 6passengerDirection = "UP"return = 1

Elevator 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 = 2

Elevator 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 = 0

Elevators 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 = -1

Elevator 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 states is "UP", "DOWN", or "IDLE".
  • passengerDirection is "UP" or "DOWN".
  • Every floor is a 32-bit signed integer.

More Pinterest problems

drafts saved locally
public int nearestEligibleElevator(int[] floors, String[] states, int passengerFloor, String passengerDirection) {
    // Write your code here.
}
floors[2,8,12]
states["UP","IDLE","DOWN"]
passengerFloor6
passengerDirection"UP"
expected1
checking account