Skip to content
BytePatterns

Elevator Stops in Sweep Order

MediumLow-Level Design#elevator-sweep#event-simulation~25m

Problem

An elevator starts at floor start, heading up, and receives floor requests as (time, floor) pairs. It moves one floor per time unit and stops take no time. At every tick it first learns the requests that have arrived by now, then serves the current floor if it was requested, then decides where to go: it keeps its direction while any request lies ahead, reverses when all remaining requests are behind it, and stays put when there are none. Return the stops as (time, floor) pairs in the order they happen. There are up to 1,000 requests.

Examples

Input:  start = 3, requests = [(0, 5), (0, 1), (1, 4), (6, 2)]
Output: [(1, 4), (2, 5), (6, 1), (7, 2)]
Why:    it finishes the upward sweep first, and passes floor 2 one tick before it is requested
Input:  start = 0, requests = [(0, 3), (2, 1), (10, 6)]
Output: [(3, 3), (5, 1), (15, 6)]
Why:    floor 1 is requested behind the car, so it waits for the reversal; then the car idles until 10
Input:  start = 4, requests = [(0, 4)]
Output: [(0, 4)]
Why:    edge case, a request for the floor the car is on is served at once

Hints

0 / 3

Stuck on the idea rather than the code? Elevator Controller covers it.