Scheduling Algorithms (FCFS, SCAN, LOOK)
Problem Statement
When an elevator receives multiple requests, it must decide the order in which to serve them. This decision directly impacts:
- Average wait time — how long passengers wait before the elevator arrives
- Total travel distance — how many floors the elevator traverses
- Fairness — whether any floor gets starved (ignored indefinitely)
Consider this scenario: an elevator is at floor 5, traveling UP, and has pending requests for floors [2, 8, 3, 7, 1, 9]. In what order should it visit these floors?
- Naive approach: Visit them in arrival order: 2→8→3→7→1→9. Total travel: 3+6+5+4+6+8 = 32 floors. The elevator bounces wildly between high and low floors.
- Smart approach: Serve all upward requests first (7→8→9), then reverse and serve downward (3→2→1). Total travel: 2+1+1+6+1+1 = 12 floors.
The difference is dramatic — the smart approach saves 62.5% of travel distance. This is exactly what SCAN and LOOK achieve. Let's explore three algorithms, starting with the simplest.
Algorithm 1: FCFS (First Come First Served)
Concept: Serve requests in the order they arrive. The first request received is the first one served, regardless of direction or proximity.
How it works:
- Maintain a FIFO queue of requests
- Dequeue the next request
- Move the elevator to that floor (ignoring other requests along the way)
- Serve the request, then dequeue the next one
Step-by-step trace:
Elevator at floor 5, requests arrive in order: [2, 8, 3, 7, 1, 9]
| Step | Current Floor | Next Request | Move To | Floors Traveled | Running Total |
|---|---|---|---|---|---|
| 1 | 5 | 2 | 2 | 3 | 3 |
| 2 | 2 | 8 | 8 | 6 | 9 |
| 3 | 8 | 3 | 3 | 5 | 14 |
| 4 | 3 | 7 | 7 | 4 | 18 |
| 5 | 7 | 1 | 1 | 6 | 24 |
| 6 | 1 | 9 | 9 | 8 | 32 |
Total travel: 32 floors
In the course's ElevatorSystem (Code Implementation) the strategy only names the next target: Elevator.move() also stops at every requested floor it passes (should_stop()). So FCFSStrategy there opens its doors at 3, 2, 7, 8, 1, 9 — 24 floors, not 32 — though it still heads for the oldest call each time.
Pros:
- Dead simple to implement
- Perfectly fair — every request is served in arrival order, no starvation possible
- Predictable — passengers know they'll be served in order
Cons:
- Extremely inefficient — the elevator bounces back and forth (the "seek" problem)
- High average wait time because the elevator often passes floors with pending requests without stopping
- Not used in real elevators — too wasteful
When to use: Only appropriate for very low traffic (1–2 requests at a time) or as a baseline for comparison. Real elevator systems never use pure FCFS.
Algorithm 2: SCAN (Elevator Algorithm)
Concept: The elevator moves in one direction, serving all requests in that direction, then reverses at the building edge and sweeps back. This is also called the elevator algorithm, after the way an elevator sweeps up through the floors and back down — like a scanner sweeping back and forth. (A real elevator turns at its last call rather than at the edge: that is LOOK, below.)
The name SCAN comes from disk scheduling (the disk head "scans" across the platter). Elevator scheduling and disk arm scheduling are the same problem: serve requests along a linear track with minimal total movement.
How it works:
- Move in the current direction (UP or DOWN)
- At each floor, check if there's a pending request — if yes, stop and serve it
- Continue until you reach the building edge (top floor for UP, bottom floor for DOWN)
- Reverse direction at the building edge, even if there are no requests at the edge
- Sweep back, serving requests in the opposite direction
Step-by-step trace:
Elevator at floor 5, going UP, building has floors 1–10, requests: [2, 8, 3, 7, 1, 9]
Phase 1: Sweep UP (from floor 5 to floor 10)
| Step | Current Floor | Action | Floors Traveled | Running Total |
|---|---|---|---|---|
| 1 | 5→7 | Serve floor 7 | 2 | 2 |
| 2 | 7→8 | Serve floor 8 | 1 | 3 |
| 3 | 8→9 | Serve floor 9 | 1 | 4 |
| 4 | 9→10 | Reach building edge (reverse) | 1 | 5 |
Phase 2: Sweep DOWN (from floor 10 to floor 1)
| Step | Current Floor | Action | Floors Traveled | Running Total |
|---|---|---|---|---|
| 5 | 10→3 | Serve floor 3 | 7 | 12 |
| 6 | 3→2 | Serve floor 2 | 1 | 13 |
| 7 | 2→1 | Serve floor 1 | 1 | 14 |
Total travel: 14 floors (vs. 32 for FCFS — 56% reduction!)
Pros:
- Much more efficient than FCFS — avoids unnecessary direction changes
- Guarantees no starvation — every floor is visited in each sweep
- Simple to understand and implement
Cons:
- Wastes travel at the edges — in our example, the elevator went to floor 10 even though the highest request was floor 9. That trip — up to 10 and back down to 9 — wastes 2 floors.
- Requests near the edge just visited have the longest wait time (they were just passed and must wait for the full sweep to return)
The SCAN disadvantage that LOOK fixes: In the trace above, the elevator traveled from floor 9 to floor 10 (the building edge) before reversing — but there was no request at floor 10. LOOK solves this by reversing at the last request instead of the building edge.
Algorithm 3: LOOK (Optimized SCAN)
Concept: Like SCAN, but the elevator reverses at the last request in the current direction instead of the building edge. It "looks" ahead to see if there are more requests before continuing.
LOOK is what most real elevator systems use (or a variant of it). It has all of SCAN's benefits without the wasted travel to empty edges.
How it works:
- Move in the current direction
- At each floor, check if there's a pending request — if yes, stop and serve it
- Before moving to the next floor: look ahead. If there are no more requests in this direction, reverse immediately
- Sweep back, serving requests in the opposite direction
Step-by-step trace:
Elevator at floor 5, going UP, requests: [2, 8, 3, 7, 1, 9]
Phase 1: Sweep UP (from floor 5 to last upward request)
| Step | Current Floor | Action | Floors Traveled | Running Total |
|---|---|---|---|---|
| 1 | 5→7 | Serve floor 7 | 2 | 2 |
| 2 | 7→8 | Serve floor 8 | 1 | 3 |
| 3 | 8→9 | Serve floor 9 (last UP request → reverse) | 1 | 4 |
Phase 2: Sweep DOWN (from floor 9 to last downward request)
| Step | Current Floor | Action | Floors Traveled | Running Total |
|---|---|---|---|---|
| 4 | 9→3 | Serve floor 3 | 6 | 10 |
| 5 | 3→2 | Serve floor 2 | 1 | 11 |
| 6 | 2→1 | Serve floor 1 (last DOWN request → idle) | 1 | 12 |
Total travel: 12 floors (vs. 14 for SCAN, vs. 32 for FCFS)
LOOK saved 2 floors compared to SCAN by not traveling to the building edges. In a 50-floor building, the savings would be much more significant.
Pros:
- Most efficient of the three algorithms
- No wasted travel to empty building edges
- Still guarantees no starvation (every pending request is served in the next sweep)
- Used by most real elevator systems
Cons:
- Slightly more complex to implement than SCAN (needs to check if requests exist ahead)
- Requests near the reversal point still have relatively high wait times
Algorithm Comparison
Let's compare all three algorithms with the same scenario:
Setup: Elevator at floor 5, going UP. Building: floors 1–10. Requests: [2, 8, 3, 7, 1, 9]
| Algorithm | Visit Order | Total Travel | Wasted Movement |
|---|---|---|---|
| FCFS | 2→8→3→7→1→9 | 32 floors | 20 floors (bouncing) |
| SCAN | 7→8→9→10→3→2→1 | 14 floors | 2 floors (up to the edge at 10 and back) |
| LOOK | 7→8→9→3→2→1 | 12 floors | 0 floors |
Key insight: FCFS ignores spatial locality. SCAN and LOOK exploit it — they serve requests that are "on the way" without extra cost. The difference between SCAN and LOOK is minimal for small buildings but compounds in tall buildings.
Race the Three Algorithms
Run the comparison yourself. One car per algorithm starts at floor 5 going up, with the same calls — 2, 8, 3, 7, 1, 9 in arrival order — and each travels a floor per tick. The chart draws each car's floor against the floors it has travelled, so the longer line is the one that travelled more; the code panel lights the lines of each get_next_stop() call in Python or Java. Turn on Ask me first to predict a car's next stop, change the calls, the start and the direction to make SCAN waste floors or FCFS beat LOOK, and switch FCFS to our ElevatorSystem, where move() also stops at every requested floor it passes.

Implementation
Here's the implementation of all three scheduling algorithms. Each implements the SchedulingStrategy interface, making them interchangeable via the Strategy Pattern. This interface is the stop-picking half, on plain floor numbers — get_next_stop(current_floor, direction, requests) — so the three can be compared on their own; in the Code Implementation the same strategies also pick the car (select_elevator), and get_next_stop takes the Elevator.
from abc import ABC, abstractmethod
from enum import Enum
from typing import List, Optional
from collections import deque
class Direction(Enum):
UP = "UP"
DOWN = "DOWN"
IDLE = "IDLE"
class Request:
def __init__(self, source_floor: int, destination_floor: int, direction: Direction):
self.source_floor = source_floor
self.destination_floor = destination_floor
self.direction = direction
def __repr__(self) -> str:
return f"Request(src={self.source_floor}, dest={self.destination_floor}, dir={self.direction.value})"
class SchedulingStrategy(ABC):
"""Interface for elevator scheduling algorithms."""
@abstractmethod
def get_next_stop(self, current_floor: int, direction: Direction,
requests: List[int]) -> Optional[int]:
"""Determine the next floor the elevator should stop at.
Args:
current_floor: The elevator's current position.
direction: The elevator's current travel direction.
requests: List of pending destination floors.
Returns:
The next floor to stop at, or None if no requests.
"""
pass
class FCFSStrategy(SchedulingStrategy):
"""First Come First Served — serve requests in arrival order."""
def get_next_stop(self, current_floor: int, direction: Direction,
requests: List[int]) -> Optional[int]:
if not requests:
return None
# Always return the first request in the queue (arrival order)
return requests[0]
class SCANStrategy(SchedulingStrategy):
"""SCAN (Elevator Algorithm) — sweep to building edge, then reverse."""
def __init__(self, min_floor: int, max_floor: int):
self.min_floor = min_floor # the building's edges: the sweep goes on to them before reversing
self.max_floor = max_floor
def get_next_stop(self, current_floor: int, direction: Direction,
requests: List[int]) -> Optional[int]:
if not requests:
return None
if direction == Direction.UP:
# Serve the closest floor ABOVE current in the UP direction
up_requests = sorted([f for f in requests if f >= current_floor])
if up_requests:
return up_requests[0]
# No more UP requests — sweep on to the building edge first
if current_floor < self.max_floor:
return self.max_floor
# At the edge: reverse, to the highest DOWN request
down_requests = sorted([f for f in requests if f < current_floor], reverse=True)
if down_requests:
return down_requests[0]
elif direction == Direction.DOWN:
# Serve the closest floor BELOW current in the DOWN direction
down_requests = sorted([f for f in requests if f <= current_floor], reverse=True)
if down_requests:
return down_requests[0]
# No more DOWN requests — sweep on to the building edge first
if current_floor > self.min_floor:
return self.min_floor
# At the edge: reverse, to the lowest UP request
up_requests = sorted([f for f in requests if f > current_floor])
if up_requests:
return up_requests[0]
else: # IDLE — pick the closest request in either direction
return min(requests, key=lambda f: abs(f - current_floor))
return None
class LOOKStrategy(SchedulingStrategy):
"""LOOK — like SCAN but reverses at the last request, not the building edge."""
def get_next_stop(self, current_floor: int, direction: Direction,
requests: List[int]) -> Optional[int]:
if not requests:
return None
if direction == Direction.UP:
# Serve the closest floor ABOVE current
up_requests = sorted([f for f in requests if f >= current_floor])
if up_requests:
return up_requests[0]
# No UP requests — LOOK ahead finds nothing, reverse immediately
down_requests = sorted([f for f in requests if f < current_floor], reverse=True)
if down_requests:
return down_requests[0]
elif direction == Direction.DOWN:
# Serve the closest floor BELOW current
down_requests = sorted([f for f in requests if f <= current_floor], reverse=True)
if down_requests:
return down_requests[0]
# Reverse immediately
up_requests = sorted([f for f in requests if f > current_floor])
if up_requests:
return up_requests[0]
else: # IDLE
return min(requests, key=lambda f: abs(f - current_floor))
return None
# --- Demonstration: Compare all three algorithms ---
def simulate(strategy: SchedulingStrategy, start: int, direction: Direction,
requests: List[int]) -> tuple:
"""Simulate an elevator serving all requests and return (visit_order, total_travel)."""
current = start
remaining = list(requests)
visit_order = []
total_travel = 0
current_dir = direction
while remaining:
next_floor = strategy.get_next_stop(current, current_dir, remaining)
if next_floor is None:
break
total_travel += abs(next_floor - current)
visit_order.append(next_floor)
# Update direction based on movement
if next_floor > current:
current_dir = Direction.UP
elif next_floor < current:
current_dir = Direction.DOWN
current = next_floor
if next_floor in remaining: # SCAN's turn at the building edge is not a request
remaining.remove(next_floor)
return visit_order, total_travel
# Test with our example
requests = [2, 8, 3, 7, 1, 9]
start_floor = 5
start_direction = Direction.UP
for name, strategy in [
("FCFS", FCFSStrategy()),
("SCAN", SCANStrategy(min_floor=1, max_floor=10)),
("LOOK", LOOKStrategy()),
]:
order, travel = simulate(strategy, start_floor, start_direction, requests)
print(f"{name}: order={order}, total_travel={travel}")
# Output:
# FCFS: order=[2, 8, 3, 7, 1, 9], total_travel=32
# SCAN: order=[7, 8, 9, 10, 3, 2, 1], total_travel=14
# LOOK: order=[7, 8, 9, 3, 2, 1], total_travel=12import java.util.*;
import java.util.stream.Collectors;
enum Direction {
UP, DOWN, IDLE
}
interface SchedulingStrategy {
/**
* Determine the next floor the elevator should stop at.
*
* @param currentFloor The elevator's current position.
* @param direction The elevator's current travel direction.
* @param requests List of pending destination floors.
* @return The next floor to stop at, or -1 if no requests.
*/
int getNextStop(int currentFloor, Direction direction, List<Integer> requests);
}
class FCFSStrategy implements SchedulingStrategy {
@Override
public int getNextStop(int currentFloor, Direction direction, List<Integer> requests) {
if (requests.isEmpty()) return -1;
return requests.get(0); // First in queue
}
}
class SCANStrategy implements SchedulingStrategy {
private final int minFloor;
private final int maxFloor;
public SCANStrategy(int minFloor, int maxFloor) {
this.minFloor = minFloor;
this.maxFloor = maxFloor;
}
@Override
public int getNextStop(int currentFloor, Direction direction, List<Integer> requests) {
if (requests.isEmpty()) return -1;
if (direction == Direction.UP) {
// Closest floor above
OptionalInt next = requests.stream()
.mapToInt(Integer::intValue)
.filter(f -> f >= currentFloor)
.min();
if (next.isPresent()) return next.getAsInt();
// Nothing above: sweep on to the building edge first
if (currentFloor < maxFloor) return maxFloor;
// At the edge — reverse: highest floor below
return requests.stream()
.mapToInt(Integer::intValue)
.filter(f -> f < currentFloor)
.max()
.orElse(-1);
} else if (direction == Direction.DOWN) {
// Closest floor below
OptionalInt next = requests.stream()
.mapToInt(Integer::intValue)
.filter(f -> f <= currentFloor)
.max();
if (next.isPresent()) return next.getAsInt();
// Nothing below: sweep on to the building edge first
if (currentFloor > minFloor) return minFloor;
// At the edge — reverse: lowest floor above
return requests.stream()
.mapToInt(Integer::intValue)
.filter(f -> f > currentFloor)
.min()
.orElse(-1);
} else { // IDLE — pick closest
return requests.stream()
.min(Comparator.comparingInt(f -> Math.abs(f - currentFloor)))
.orElse(-1);
}
}
}
class LOOKStrategy implements SchedulingStrategy {
@Override
public int getNextStop(int currentFloor, Direction direction, List<Integer> requests) {
if (requests.isEmpty()) return -1;
if (direction == Direction.UP) {
OptionalInt next = requests.stream()
.mapToInt(Integer::intValue)
.filter(f -> f >= currentFloor)
.min();
if (next.isPresent()) return next.getAsInt();
// LOOK: reverse immediately at last request
return requests.stream()
.mapToInt(Integer::intValue)
.filter(f -> f < currentFloor)
.max()
.orElse(-1);
} else if (direction == Direction.DOWN) {
OptionalInt next = requests.stream()
.mapToInt(Integer::intValue)
.filter(f -> f <= currentFloor)
.max();
if (next.isPresent()) return next.getAsInt();
return requests.stream()
.mapToInt(Integer::intValue)
.filter(f -> f > currentFloor)
.min()
.orElse(-1);
} else { // IDLE
return requests.stream()
.min(Comparator.comparingInt(f -> Math.abs(f - currentFloor)))
.orElse(-1);
}
}
}
// --- Demonstration ---
public class SchedulingDemo {
public static void main(String[] args) {
List<Integer> requests = Arrays.asList(2, 8, 3, 7, 1, 9);
int startFloor = 5;
Direction startDir = Direction.UP;
SchedulingStrategy[] strategies = {
new FCFSStrategy(),
new SCANStrategy(1, 10),
new LOOKStrategy()
};
String[] names = {"FCFS", "SCAN", "LOOK"};
for (int i = 0; i < strategies.length; i++) {
List<Integer> remaining = new ArrayList<>(requests);
List<Integer> visitOrder = new ArrayList<>();
int current = startFloor;
int totalTravel = 0;
Direction dir = startDir;
while (!remaining.isEmpty()) {
int next = strategies[i].getNextStop(current, dir, remaining);
if (next == -1) break;
totalTravel += Math.abs(next - current);
visitOrder.add(next);
if (next > current) dir = Direction.UP;
else if (next < current) dir = Direction.DOWN;
current = next;
remaining.remove(Integer.valueOf(next)); // no-op for SCAN's turn at the building edge
}
System.out.printf("%s: order=%s, total_travel=%d%n",
names[i], visitOrder, totalTravel);
}
}
}Complexity Analysis
Time Complexity (per getNextStop call):
| Algorithm | Time | Explanation |
|---|---|---|
| FCFS | O(1) | Always returns the first element in the queue |
| SCAN | O(n log n) in the Python, O(n) in the Java | The Python filters and sorts the requests by direction; the Java finds the nearest floor ahead in one pass (min()/max()) |
| LOOK | Same as SCAN | The same filters, without the edge |
Total travel (for n requests across m floors):
| Algorithm | Worst Case Travel | Average Travel |
|---|---|---|
| FCFS | O(n × m) | High — elevator bounces |
| SCAN | O(2m) | Low — at most two full sweeps |
| LOOK | O(2m) | Lowest — no edge waste |
The critical insight: SCAN and LOOK guarantee that total travel is bounded by 2 × building height regardless of how many requests there are. FCFS travel grows linearly with the number of requests.
Space: O(n) for all three — storing the request queue.
Optimization note: In a production system, SCAN and LOOK would keep the requests sorted — a TreeSet in Java; in Python a list kept sorted with bisect, or SortedList from the sortedcontainers package. The next stop ahead is then one lookup, ceiling()/floor() or a bisect: O(log n) per call. Inserting is O(log n) in the TreeSet and the SortedList; bisect.insort finds the place in O(log n) but shifts the list, O(n).
Connecting to the Strategy Pattern
All three algorithms implement the same SchedulingStrategy interface. This is the Strategy Pattern (Fundamentals S12) in action:
- Context:
Dispatcher— holds the strategy and asks it which car takes each hall call (select_elevator()); each step, everyElevator'smove()is handed the same strategy and asks it for its next stop (get_next_stop()). Neither knows which algorithm runs - Strategy interface:
SchedulingStrategy— definesselectElevator()andgetNextStop()(this lesson's listing keeps thegetNextStop()half) - Concrete strategies:
FCFSStrategy,SCANStrategy,LOOKStrategy
Swapping algorithms is one line of code:
# Switch from FCFS to LOOK at runtime
dispatcher.set_strategy(LOOKStrategy())The Dispatcher, Elevator, Floor, and every other class remain unchanged. This is the Open/Closed Principle (Fundamentals S6) — the system is open for new algorithms but closed for modification.
Want to add a Nearest-Car algorithm that always picks the closest idle elevator? Implement SchedulingStrategy, plug it in. Zero changes to existing code.
This same Strategy Pattern approach is used for pricing in the Parking Lot (DP1) and Car Rental (DP12), for matching in the Ride-Sharing Service (DP22), and for split types in Splitwise (DP15). The elevator scheduling problem makes the pattern's value most visible because the algorithms have such different performance characteristics.