call(back)
Algorithms & Data StructureseasySign in to star problems

Select the Nearest Eligible Elevator

A building has elevators, each described by:

{ "id": 1, "floor": 4, "direction": "up" | "down" | "idle", "serviced": [1, 3, 5] }

(serviced = floors this elevator stops at — service and freight elevators skip floors.)

A hail arrives: (floor, direction). An elevator is eligible if it services that floor AND is either idle, or already moving in the hailed direction toward the floor (an "up" elevator at or below the hail floor; a "down" elevator at or above it). Among eligible elevators return the id of the nearest (minimum |currentFloor - hailFloor|); break ties by lowest id. Return -1 if none.

Hints

Hint 1

Write the eligibility predicate as its own small check with early rejections — services the floor, then direction: idle always matches; a moving elevator must match the hailed direction and be on the correct side (at the hail floor counts as toward).

Hint 2

One linear scan keeping the best (distance, id) pair is optimal — every elevator must be examined once. The pair comparison gives the lowest-id tie-break for free.

Asked at