An office tower's controller has to decide which elevator answers when someone presses a hall button.
Implement call_elevator(elevators: list[list[str]], request: list[str]) -> int.
- Each elevator is
[floor, state]:flooris a whole number written as a string ("7","12","-2"for a basement level) andstateis"up","down"or"idle". requestis[floor, direction]: the floor where the passenger is waiting (same string format) and the way they want to go,"up"or"down".
An elevator is eligible when:
- it is
"idle"(it can go anywhere), or - it is moving
"up", the passenger wants to go"up", and the elevator is at or below the passenger's floor, or - it is moving
"down", the passenger wants to go"down", and the elevator is at or above the passenger's floor.
A moving elevator never turns around for a call: one going the other way, or one that has already passed the floor, isn't eligible.
Among the eligible elevators, return the index of the one closest to the passenger's floor (smallest absolute floor difference). If several are equally close, return the smallest index. If none is eligible, return -1.
call_elevator([["3", "up"], ["9", "idle"], ["6", "down"]], ["5", "up"]) # 0 (distance 2; the idle one is 4 away)
call_elevator([["3", "up"], ["9", "idle"], ["6", "down"]], ["5", "down"]) # 2 (distance 1)
call_elevator([["8", "up"], ["2", "down"]], ["5", "up"]) # -1
call_elevator([["9", "up"]], ["10", "up"]) # 0
Floors are numbers: compare them as integers, not as strings ("9" is below "10").
Constraints: 0 <= len(elevators) <= 100,000, floors between -1000 and 1000.
Show hint
One pass: parse each floor with int, check the three eligibility rules, and keep the best (distance, index) seen so far.