KatInterview

One-Car Sweep Scheduler: Order the Elevator Stops

Heaps, Sorting & SearchAuto-graded · 22 test cases
MediumAuto-gradedHeaps, Sorting & Searchheappriority-queuesorting

Last 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

  1. 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.
  2. 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.
  3. 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_floor is an integer.
  • direction is the string "up" or "down".
  • pending_floors is a list of integers and may be empty or contain duplicates.
  • Each floor appears at most once in the output.
  • The order of pending_floors does 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.