One-Car Sweep Scheduler: Order the Elevator Stops
Heaps, Sorting & SearchAuto-graded · 22 test casesLast updated
Order a single elevator's pending floor requests using a one-reversal sweep policy with a priority queue, merging duplicates and respecting the starting direction.
One-Car Sweep Scheduler
A single elevator sits at a given floor and is committed to travelling either "up" or "down". A list of floor requests is waiting. Your task is to compute the order in which the elevator stops at floors, using a sweep policy that avoids needless back-and-forth travel.
Policy
- Current direction first. The elevator first serves every requested floor that lies in its direction of travel, including its current floor. These are served in order of distance from the current floor, nearest first.
- Going
"up": floors>= current_floor, in ascending order. - Going
"down": floors<= current_floor, in descending order.
- Going
- Reverse once. After the first group, the elevator reverses and serves all remaining floors (those that were behind it), again nearest first from the turnaround point.
- After going up first: the remaining floors are
< current_floor, in descending order. - After going down first: the remaining floors are
> current_floor, in ascending order.
- After going up first: the remaining floors are
- Merge duplicates. If the same floor is requested several times, it appears only once in the output.
The elevator never reverses more than once, and no new requests arrive during the run.
Task
Implement a function that takes the current floor, the direction of travel ("up" or "down") and the list of pending floor requests, and returns the list of floors in the order they are stopped at.
If direction is neither "up" nor "down", raise a ValueError.
If there are no pending requests, return an empty list.
Constraints
current_flooris an integer.directionis the string"up"or"down".pending_floorsis a list of integers and may be empty or contain duplicates.- Each floor appears at most once in the output.
- The order of
pending_floorsdoes not affect the result.
Examples
Example 1
Input: plan_sweep_stops(1, 'up', [1, 99, 2])
Output: [1, 2, 99]
Hints
Hint 1
Split the requests into two groups: those the elevator reaches before reversing, and those it reaches after. Which comparison with the current floor decides the group?
Hint 2
Give every request a sortable key such as (group, distance-ordered value). For an upward sweep use the floor itself in the first group and the negated floor in the second group; mirror this for downward travel.
Hint 3
Pop from a min-heap (or simply sort by the key) and skip a floor if it equals the one you just emitted. Because equal floors have equal keys, duplicates are adjacent.
Worked solution
Medium Try it yourself first — then compare your approach, complexity and edge cases.
Approach
Each request is given a sort key that encodes both which pass it belongs to and where it falls within that pass. A min-heap then yields the stops in the correct order.
- Pass number. A floor in the current direction of travel (including the current floor) gets pass
0. A floor behind the elevator gets pass1. - Position within the pass. In an upward pass, floors are visited in ascending order, so the key is the floor itself. In a downward pass, floors are visited in descending order, so the key is the negated floor.
- Heading up: pass 0 uses
floor, pass 1 (which travels down) uses-floor. - Heading down: pass 0 uses
-floor, pass 1 (which travels up) usesfloor.
- Heading up: pass 0 uses
- Duplicates. Equal floors produce identical keys, so they pop consecutively. When popping, skip a floor that equals the previously emitted one.
Why it is correct
Every floor in pass 0 lies ahead of the elevator, so visiting them nearest first is a single monotone travel in the current direction. When that pass ends, the elevator is at its farthest requested floor in that direction. Every pass 1 floor lies on the opposite side of the start, so after reversing they are all ahead of the elevator, and visiting them nearest first from the turnaround is again a single monotone travel. Tuple ordering compares the pass number first, so all pass 0 floors precede all pass 1 floors, and the second key component orders each pass correctly. Since duplicates are adjacent in pop order, one comparison with the last emitted floor removes them all.
For the sample, start_floor = 1, heading up, requests [1, 99, 2]: all three are in pass 0 with keys 1, 99, 2, giving the order [1, 2, 99]. The elevator reaches 2 before 99 simply because of the heap ordering.
Complexity
- Time: O(n log n) for n requests (n pushes and n pops).
- Space: O(n) for the heap and the output.
Reference solution
import heapq
from typing import List
def plan_sweep_stops(start_floor: int, heading: str, requests: List[int]) -> List[int]:
"""Return the order in which a single elevator stops at the requested floors."""
if heading not in ("up", "down"):
raise ValueError("heading must be 'up' or 'down'")
heap = []
for floor in requests:
if heading == "up":
if floor >= start_floor:
key = (0, floor, floor)
else:
key = (1, -floor, floor)
else:
if floor <= start_floor:
key = (0, -floor, floor)
else:
key = (1, floor, floor)
heapq.heappush(heap, key)
order = []
last = None
has_last = False
while heap:
_, _, floor = heapq.heappop(heap)
if not has_last or floor != last:
order.append(floor)
last = floor
has_last = True
return order