Bird
Raised Fist0
LLDsystem_design~15 mins

Elevator, Floor, Request classes in LLD - Deep Dive

Choose your learning style10 modes available

Start learning this pattern below

Jump into concepts and practice - no test required

or
Recommended
Test this pattern10 questions across easy, medium, and hard to know if this pattern is strong
Overview - Elevator, Floor, Request classes
What is it?
Elevator, Floor, and Request classes are the basic building blocks to model an elevator system in software. The Elevator class represents the moving cabin that carries people. The Floor class represents each level in a building where people can wait or exit. The Request class captures a user's desire to move from one floor to another. Together, these classes help simulate and control elevator behavior.
Why it matters
Without these classes, it would be very hard to organize and manage the complex interactions in an elevator system. They solve the problem of tracking where elevators are, who wants to go where, and how to move efficiently. Without this structure, elevator control would be chaotic, slow, and unsafe, leading to long waits and confusion.
Where it fits
Before learning these classes, you should understand basic object-oriented programming concepts like classes and objects. After this, you can learn about elevator scheduling algorithms and system optimization. This topic fits early in designing a low-level system model for elevators.
Mental Model
Core Idea
Elevator, Floor, and Request classes work together like parts of a building's transportation system, where floors are stops, requests are ride orders, and elevators are vehicles fulfilling those orders.
Think of it like...
Think of a taxi service in a city: Floors are the taxi stands, Requests are people calling for a ride, and Elevators are the taxis that pick up and drop off passengers.
┌───────────┐       ┌───────────┐       ┌────────────┐
│  Floor    │◄─────►│ Request   │◄─────►│ Elevator   │
│ (location)│       │ (from, to)│       │ (state, pos)│
└───────────┘       └───────────┘       └────────────┘
Build-Up - 7 Steps
1
FoundationDefine the Floor class basics
🤔
Concept: Introduce the Floor class to represent building levels with unique identifiers.
The Floor class holds a floor number or name. It can track waiting passengers or requests originating from that floor. Example attributes: floorNumber, waitingRequests.
Result
You can create Floor objects representing each level in a building, which serve as fixed points for elevator stops.
Understanding floors as distinct objects helps organize where requests come from and where elevators must stop.
2
FoundationCreate the Request class structure
🤔
Concept: Introduce the Request class to capture user travel desires between floors.
Request objects store the source floor and destination floor. They represent a passenger's intent to move from one floor to another. Attributes: sourceFloor, destinationFloor, direction.
Result
You can now represent individual ride requests clearly, which elevators will later process.
Modeling requests separately clarifies the system's input and allows flexible handling of passenger demands.
3
IntermediateBuild the Elevator class core
🤔
Concept: Introduce the Elevator class to represent the moving cabin with state and position.
Elevator objects track current floor, direction (up/down/idle), and a list of assigned requests. They have methods to move, open doors, and update status.
Result
You can simulate elevator movement and manage which requests it serves.
Elevators as active objects with state enable dynamic response to requests and real-time control.
4
IntermediateLink Requests to Floors and Elevators
🤔Before reading on: Do you think requests should be stored only in floors, only in elevators, or both? Commit to your answer.
Concept: Show how requests originate at floors and get assigned to elevators for fulfillment.
Requests start at a Floor's waiting list. The system assigns requests to an Elevator's queue. Elevators pick up passengers at source floors and drop them at destination floors.
Result
Requests flow from floors to elevators, enabling coordinated movement and service.
Understanding this flow is key to designing efficient elevator control and avoiding lost or ignored requests.
5
IntermediateManage Elevator state transitions
🤔Before reading on: Should elevators always move continuously, or can they pause and change direction? Commit to your answer.
Concept: Explain how elevators change states: moving, stopped, door open, idle.
Elevators transition between states based on requests and position. They move towards next request floor, stop to open doors, and update direction or idle if no requests remain.
Result
Elevators behave realistically, responding to passenger needs and optimizing travel.
Modeling states prevents unrealistic elevator behavior and supports smooth operation.
6
AdvancedImplement request scheduling logic
🤔Before reading on: Do you think elevators should serve requests strictly in order received or optimize for direction and proximity? Commit to your answer.
Concept: Introduce scheduling algorithms to decide which requests an elevator serves and in what order.
Elevators prioritize requests going in their current direction to minimize travel time. They may reorder requests to pick up passengers efficiently. This reduces wait and travel times.
Result
Elevator systems become more efficient and user-friendly.
Scheduling logic is the heart of elevator efficiency and user satisfaction.
7
ExpertHandle concurrent requests and edge cases
🤔Before reading on: Can multiple elevators serve the same request simultaneously? Should requests be duplicated or uniquely assigned? Commit to your answer.
Concept: Discuss concurrency, request conflicts, and system robustness in multi-elevator setups.
In multi-elevator systems, requests must be assigned uniquely to avoid duplication. The system handles simultaneous requests, elevator failures, and priority overrides. Synchronization and state consistency are critical.
Result
The elevator system scales to real buildings with many elevators and users.
Handling concurrency and edge cases ensures reliability and scalability in production elevator systems.
Under the Hood
Each class encapsulates data and behavior: Floors hold waiting requests; Requests carry travel intent; Elevators maintain current state and assigned requests. The system cycles through events: new requests arrive, elevators update position, and requests are assigned and completed. Internally, elevators use queues or priority structures to manage requests and state machines to track movement and door operations.
Why designed this way?
This design separates concerns clearly: floors represent static locations, requests represent dynamic user input, and elevators represent active agents. This modularity simplifies development, testing, and scaling. Alternatives like monolithic designs mix responsibilities and become hard to maintain. The chosen approach aligns with object-oriented principles and real-world analogies.
┌─────────────┐       ┌─────────────┐       ┌───────────────┐
│   Floor     │──────▶│  Request    │──────▶│   Elevator    │
│ (static)    │       │ (dynamic)   │       │ (active agent) │
│ - floorNum  │       │ - fromFloor │       │ - currentFloor│
│ - waitList  │       │ - toFloor   │       │ - direction   │
└─────────────┘       └─────────────┘       └───────────────┘
       ▲                     │                      │
       │                     │                      │
       └─────────────────────┴──────────────────────┘
Myth Busters - 4 Common Misconceptions
Quick: Do you think an elevator can serve requests in any order without affecting efficiency? Commit yes or no.
Common Belief:Elevators can serve requests in the order they arrive without any scheduling.
Tap to reveal reality
Reality:Serving requests blindly in arrival order leads to inefficient travel, longer wait times, and wasted energy.
Why it matters:Ignoring scheduling causes slow service and frustrated users, especially in busy buildings.
Quick: Do you think floors actively control elevators by themselves? Commit yes or no.
Common Belief:Floors control elevators by sending direct commands to move up or down.
Tap to reveal reality
Reality:Floors only generate requests; elevators decide movement based on assigned requests and internal logic.
Why it matters:Misunderstanding control flow can lead to poor system design and bugs where floors try to micromanage elevators.
Quick: Can multiple elevators pick the same request simultaneously? Commit yes or no.
Common Belief:Multiple elevators can serve the same request at the same time to speed up service.
Tap to reveal reality
Reality:Requests must be uniquely assigned to one elevator to avoid duplication and confusion.
Why it matters:Duplicated service wastes resources and can cause inconsistent system states.
Quick: Do you think the Elevator class only needs to know its current floor? Commit yes or no.
Common Belief:Elevators only track their current floor; direction and requests are managed elsewhere.
Tap to reveal reality
Reality:Elevators must track direction, assigned requests, and door states to operate correctly.
Why it matters:Incomplete elevator state leads to unrealistic behavior and poor user experience.
Expert Zone
1
Elevator direction state is not just up or down; it includes idle and door-open states that affect scheduling decisions.
2
Requests can be grouped by direction to optimize pickups, but this grouping must dynamically update as new requests arrive.
3
Handling emergency overrides (e.g., fire alarms) requires temporarily suspending normal request processing and controlling elevators differently.
When NOT to use
This class-based approach is less suitable for extremely large-scale distributed elevator systems where microservices or event-driven architectures better handle complexity. In such cases, message queues and distributed state stores replace direct object interactions.
Production Patterns
Real-world elevator systems use these classes as part of a layered architecture: hardware interface layers communicate with Elevator objects, scheduling services assign Requests, and monitoring dashboards track Floor statuses. Patterns like command queues, state machines, and observer patterns are common.
Connections
State Machine
Elevator class behavior is modeled as a state machine controlling movement and door states.
Understanding state machines clarifies how elevators transition smoothly between moving, stopping, and idling.
Queue Data Structure
Request handling uses queues to manage order and priority of service.
Knowing queue operations helps design efficient request scheduling and processing.
Traffic Control Systems
Elevator scheduling shares principles with traffic light control and vehicle routing.
Studying traffic systems reveals strategies to optimize flow and reduce wait times in elevators.
Common Pitfalls
#1Assigning requests to multiple elevators simultaneously.
Wrong approach:elevator1.assignRequest(request); elevator2.assignRequest(request);
Correct approach:if (elevator1.isBetterFor(request)) { elevator1.assignRequest(request); } else { elevator2.assignRequest(request); }
Root cause:Misunderstanding that requests must be uniquely assigned to avoid duplication and confusion.
#2Elevator moves without checking assigned requests.
Wrong approach:elevator.moveUp(); // moves blindly without request checks
Correct approach:if (elevator.hasPendingRequests()) { elevator.moveTowardsNextRequest(); } else { elevator.idle(); }
Root cause:Ignoring the elevator's request queue leads to inefficient or meaningless movement.
#3Floor class tries to control elevator movement directly.
Wrong approach:floor.sendMoveCommand(elevator, 'up');
Correct approach:floor.addRequest(request); elevator.processRequests();
Root cause:Confusing roles causes tight coupling and breaks modular design.
Key Takeaways
Elevator, Floor, and Request classes model the core components of an elevator system clearly and modularly.
Requests represent passenger intents and flow from floors to elevators for processing.
Elevators maintain state and schedule requests to optimize travel and reduce wait times.
Proper assignment and scheduling of requests are critical for efficient and realistic elevator behavior.
Understanding internal states and concurrency prepares you for building scalable, robust elevator systems.

Practice

(1/5)
1. What is the primary role of the Request class in an elevator system?
easy
A. To store the floor number and direction of a user's request
B. To move the elevator between floors
C. To open and close the elevator doors
D. To track the number of elevators in the building

Solution

  1. Step 1: Understand the purpose of Request class

    The Request class holds information about where a user wants to go and in which direction.
  2. Step 2: Compare roles of other classes

    Elevator moves and Floor represents building levels, but Request stores user input details.
  3. Final Answer:

    To store the floor number and direction of a user's request -> Option A
  4. Quick Check:

    Request = user floor and direction [OK]
Hint: Request class holds user floor and direction info [OK]
Common Mistakes:
  • Confusing Request with Elevator movement
  • Thinking Request controls doors
  • Mixing Request with Floor class responsibilities
2. Which of the following is the correct way to define a Request class constructor in Python to store floor and direction?
easy
A. def Request(floor, direction): self.floor = floor; self.direction = direction
B. def __init__(self, floor, direction): self.floor = floor; self.direction = direction
C. def __init__(floor, direction): self.floor = floor; self.direction = direction
D. def __init__(self): floor = None; direction = None

Solution

  1. Step 1: Recall Python constructor syntax

    Python constructors use def __init__(self, ...) and assign attributes with self.attribute = value.
  2. Step 2: Check each option

    def __init__(self, floor, direction): self.floor = floor; self.direction = direction correctly uses self and assigns floor and direction. Others miss self or parameters.
  3. Final Answer:

    def __init__(self, floor, direction): self.floor = floor; self.direction = direction -> Option B
  4. Quick Check:

    Constructor with self and attributes = def __init__(self, floor, direction): self.floor = floor; self.direction = direction [OK]
Hint: Python constructors need self parameter and attribute assignment [OK]
Common Mistakes:
  • Omitting self parameter
  • Using class name as constructor
  • Not assigning attributes to self
3. Given this Python snippet, what will be printed?
class Request:
    def __init__(self, floor, direction):
        self.floor = floor
        self.direction = direction

r = Request(5, 'up')
print(r.floor, r.direction)
medium
A. Error: missing self
B. floor direction
C. 5 up
D. None None

Solution

  1. Step 1: Understand object creation and attribute assignment

    The Request object r is created with floor=5 and direction='up'. These are stored in attributes.
  2. Step 2: Print attributes

    Printing r.floor and r.direction outputs 5 and 'up' respectively.
  3. Final Answer:

    5 up -> Option C
  4. Quick Check:

    Attributes print as assigned = 5 up [OK]
Hint: Print object attributes to see stored values [OK]
Common Mistakes:
  • Expecting attribute names instead of values
  • Confusing class variables with instance variables
  • Assuming error without checking code carefully
4. Identify the error in this Elevator class snippet:
class Elevator:
    def __init__(self, current_floor):
        self.current_floor = current_floor

    def move_to(self, floor):
        current_floor = floor
medium
A. Indentation error in move_to method
B. Missing return statement in move_to method
C. Constructor should not have parameters
D. The move_to method updates a local variable, not the elevator's floor

Solution

  1. Step 1: Analyze move_to method

    The method assigns current_floor = floor without self., so it changes a local variable only.
  2. Step 2: Understand instance variable update

    To update the elevator's floor, it should be self.current_floor = floor.
  3. Final Answer:

    The move_to method updates a local variable, not the elevator's floor -> Option D
  4. Quick Check:

    Missing self. means local variable used [OK]
Hint: Use self. to update instance variables inside methods [OK]
Common Mistakes:
  • Forgetting self. prefix
  • Thinking return is needed to update state
  • Assuming indentation is wrong without checking
5. In designing an elevator system with Elevator, Floor, and Request classes, which approach best handles multiple simultaneous requests efficiently?
hard
A. Use a priority queue in Elevator to process requests by nearest floor and direction
B. Process requests in the order they arrive without sorting
C. Assign each request to a random elevator immediately
D. Ignore direction and always move elevators to the highest requested floor first

Solution

  1. Step 1: Understand multiple request handling

    Efficient elevator systems prioritize requests to minimize travel and wait time.
  2. Step 2: Evaluate options for request processing

    Using a priority queue to pick nearest floors and matching direction optimizes movement. Others cause inefficiency or randomness.
  3. Final Answer:

    Use a priority queue in Elevator to process requests by nearest floor and direction -> Option A
  4. Quick Check:

    Priority queue for nearest requests = Use a priority queue in Elevator to process requests by nearest floor and direction [OK]
Hint: Prioritize nearest requests with direction for efficient elevator movement [OK]
Common Mistakes:
  • Ignoring direction leads to inefficient routes
  • Random assignment causes delays
  • Processing requests strictly by arrival order wastes time