progress

~/problems / Simulation & OOP design / Simulation

Pick the elevator that answers a call

On a phone? Coding is easier on a laptop: email this problem to yourself . Meanwhile: quiz this topic or fight a boss.

easy ~10 min Pinterest

An office tower's controller decides which elevator answers a hall button.

Implement call_elevator(elevators: list[list[str]], request: list[str]) -> int. Each elevator is [floor, state] with state one of "up", "down", "idle"; request is [floor, direction] with direction "up" or "down". Floors are integers written as strings ("-2" is a basement): compare them as numbers, so "9" is below "10".

An elevator is eligible if it is "idle", or it moves the passenger's way and hasn't passed them yet: going "up" at or below their floor, or going "down" at or above it.

Return the index of the eligible elevator closest to the passenger's floor (ties: smallest index), or -1 if none is eligible.

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

Up to 100,000 elevators; floors between -1000 and 1000.

⭐ Bonus: a speed test with 100,000 elevators earns a star in a single O(n) pass.

Show hint

One pass: parse each floor with int, check eligibility, and keep the best (distance, index) so far.

Topic: Simulation. Model the process exactly; watch simultaneous updates and direction arithmetic.

Read the visual guide
0:00
Ctrl ' run · Ctrl ↵ submit
esc