Skip to content
Search lessons, topics, tests…
Esc

    ↑ ↓ moveEnter openEsc close
    Lesson1 / 14

    Module 1 · The Round and a First Design · Lesson 1 of 14

    The LLD and Machine-Coding Round in C#: How It Is Judged and a Method You Can Repeat

    What this lesson teaches

    Low-level design and machine-coding interviews test how you turn requirements into C# code. Learn what to ask, what to build, and what to leave out.

    Before designing, ask about users, use cases, limits, simultaneous requests, storage, and what is out of scope. Write down the assumptions you agree on. Those answers decide what your classes need to do.

    This first lesson gives you six steps to repeat: Clarify, Model and cut, Public API first, Build in memory, Driver and self-check, and Trade-offs. We will use a small meeting-room booker to make them concrete.

    What low-level design and machine coding involve

    In this lesson, low-level design (LLD) means choosing Room, Booking, and BookingService, connecting them, and implementing TryBook. Our example runs in one process. A process is an executing program. See Microsoft's Threads and threading for more about processes and threads.

    High-level design (HLD), often called system design, looks at a broader problem: how services, storage, and communication work across machines as demand grows. For that broader approach, read the system design interview method for .NET developers.

    The interview format changes how much you must deliver:

    FormatTypical planning rangeMain result
    LLD discussion45–60 minutesClasses, relationships, key methods, and some code
    Machine-coding round90–120 minutesWorking code, a demonstration, and often one requested change

    These are preparation ranges, not rules every interviewer follows. Confirm the actual time and expected deliverables.

    In a machine-coding round, use this practical checklist:

    • The program runs and meets the must-haves: requirements agreed as necessary for this attempt.
    • Classes have small, clear jobs.
    • A likely new requirement needs a small change, not a redesign.
    • Names explain the code without a running commentary.
    • Invalid input and edge cases give a result you chose on purpose. Edge cases are values right at a limit, such as one booking ending at 10:00 and another starting at 10:00.
    • A small program demonstrates the important behavior.
    • Additional tests help, but a separate test project should not displace the required working program unless explicitly requested.

    Working code that meets the agreed requirements beats a clever design left unfinished.

    The mistake to avoid. Do not spend a small, single-program exercise designing a network of services. Solve at the level the interviewer requested.

    In an interview, say: “Low-level design, or LLD, focuses on classes, relationships, methods, and code inside one process. High-level design, or HLD, focuses on services, storage, and scaling across machines. I would first confirm whether you want a design discussion or a working program.”

    Clarify: what do you ask before you design?

    Booking a room is the use case we implement here. Start with that user action, not class names.

    For a meeting-room booker, ask these questions:

    AreaQuestions to ask
    UsersWho books rooms? Does anyone manage the available rooms?
    Use casesMust we create bookings, cancel them, list them, or search for availability?
    LimitsHow many rooms and bookings should we expect? What makes a booking valid?
    ConcurrencyCan two booking requests arrive at the same time?
    StorageMay data stay only in memory, or must it survive a program restart?
    ScopeAre recurring meetings, notifications, and permissions required?

    For the concurrency question, ask: could two callers try to reserve the same room before either sees the other's booking?

    Separate must-haves from good-to-haves: useful additions that are not needed for the agreed demonstration. If the interviewer leaves a detail open, state your proposed rule and get agreement.

    For our example, write down these assumptions:

    • Rooms already exist. A caller can request a booking for a known room.
    • A booking has a caller-supplied unique ID, a room ID, a start, and an end.
    • The start must be earlier than the end.
    • Bookings for the same room must not overlap.
    • One booking ending at 10:00 does not clash with another starting at 10:00.
    • Calls happen one at a time. Data stays in memory and disappears when the program exits.
    • All times are given in the same time zone, for example, all in UTC.
    • Cancellation, recurring bookings, permissions, and notifications are out of scope.

    The mistake to avoid. Do not silently invent important behavior. A technically neat implementation can still solve the wrong problem if it assumes the wrong overlap or storage rules.

    In an interview, say: “Before designing, I ask who the users are, which use cases are required, the limits, whether requests can overlap, how data is stored, and what is out of scope. I write down agreed assumptions and separate must-haves from good-to-haves.”

    Model and cut: turn requirements into a few classes

    Use nouns as candidate classes and verbs as candidate methods. Then cut anything that has no responsibility in the agreed scope.

    Take this requirement: “A user books a room for a time range.” The nouns are user, room and time range. The verb is books. The action also suggests a noun: booking.

    CandidateKeep or cut?
    UserCut a separate user class for now. User details do not affect the agreed booking rules.
    RoomKeep Room to identify an available room.
    BookingKeep Booking to record an accepted reservation.
    Time rangeKeep its start and end on Booking; this exercise does not need a separate class.
    BookMake it the TryBook method on BookingService, which checks and stores requests.

    We do not need an Employee, NotificationManager, or Building yet. None helps implement the agreed booking action.

    classDiagram
        direction TB
        class Room {
            +int Id
        }
        class Booking {
            +int Id
            +int RoomId
            +DateTime Start
            +DateTime End
        }
        class BookingService {
            -List~Room~ rooms
            -List~Booking~ bookings
            +TryBook(bookingId, roomId, start, end) bool
        }
        BookingService "1" --> "*" Room : knows
        BookingService "1" *-- "*" Booking : creates and keeps

    The service knows the rooms and creates and keeps every accepted booking. Demo and Check are not drawn: they only run the example.

    Keep the design this small until a requirement gives another class a real job. Draw a small diagram, about 5 to 8 boxes. It should show what each class does, not every class you can think of.

    Public API first, then build in memory

    Here, start with the public API the caller needs: the BookingService constructor and TryBook. Decide how the caller will use them before writing their internal steps.

    Our main operation is TryBook. It returns true when a booking is accepted and false when it is rejected. Before implementing it, write the caller you want: construct the service, request a booking, and check the result.

    Next, build the simplest complete path in memory. Here that means checking the request, looking for a clash, and adding an accepted booking to a list. No database is needed for the agreed scope.

    Before running the program below, trace TryBook by hand for booking 102 (room 1, 10:00 to 11:00) and booking 103 (room 1, 09:30 to 10:00). Which comparison in the clash check decides each one?

    C#Runs
    using System;
    using System.Collections.Generic;
    using System.Linq;
    
    public static class Demo
    {
        public static void Main()
        {
            var service = new BookingService(new[] { new Room(1), new Room(2) });
            var day = new DateTime(2030, 6, 1);
            var nine = day.AddHours(9);
            var ten = day.AddHours(10);
            var eleven = day.AddHours(11);
    
            Check.Equal("First booking", true,
                service.TryBook(101, 1, nine, ten));
            Check.Equal("Adjacent booking", true,
                service.TryBook(102, 1, ten, eleven));
            Check.Equal("Same room overlap", false,
                service.TryBook(103, 1, nine.AddMinutes(30), ten));
            Check.Equal("Different room", true,
                service.TryBook(104, 2, nine, ten));
            Check.Equal("Unknown room", false,
                service.TryBook(105, 99, nine, ten));
            Check.Equal("Empty interval", false,
                service.TryBook(106, 1, ten, ten));
            Check.Equal("Reversed interval", false,
                service.TryBook(107, 1, eleven, ten));
            Check.Equal("Duplicate booking ID", false,
                service.TryBook(101, 2, ten, eleven));
        }
    }
    
    public sealed class Room
    {
        public int Id { get; }
    
        public Room(int id) => Id = id;
    }
    
    public sealed class Booking
    {
        public int Id { get; }
        public int RoomId { get; }
        public DateTime Start { get; }
        public DateTime End { get; }
    
        public Booking(int id, int roomId, DateTime start, DateTime end)
        {
            Id = id;
            RoomId = roomId;
            Start = start;
            End = end;
        }
    }
    
    public sealed class BookingService
    {
        private readonly List<Room> rooms;
        private readonly List<Booking> bookings = new List<Booking>();
    
        public BookingService(IEnumerable<Room> rooms)
        {
            this.rooms = new List<Room>(rooms);
        }
    
        public bool TryBook(int bookingId, int roomId, DateTime start, DateTime end)
        {
            if (start >= end || !rooms.Any(r => r.Id == roomId))
                return false;
    
            if (bookings.Any(b => b.Id == bookingId))
                return false;
    
            bool clashes = bookings.Any(b =>
                b.RoomId == roomId && start < b.End && b.Start < end);
    
            if (clashes)
                return false;
    
            bookings.Add(new Booking(bookingId, roomId, start, end));
            return true;
        }
    }
    
    public static class Check
    {
        public static void Equal(string name, bool expected, bool actual)
        {
            Console.WriteLine($"{(expected == actual ? "PASS" : "FAIL")}: {name}");
        }
    }
    Output
    PASS: First booking
    PASS: Adjacent booking
    PASS: Same room overlap
    PASS: Different room
    PASS: Unknown room
    PASS: Empty interval
    PASS: Reversed interval
    PASS: Duplicate booking ID

    The times and IDs are supplied explicitly, so the demonstration does not depend on the current time or randomly generated data.

    The important overlap rule is start < b.End && b.Start < end. Each booking starts before the other one ends. Both conditions must hold, and the room must match.

    For an existing booking from 09:00 to 10:00 in the same room:

    Requested timestart < b.Endb.Start < endClash?
    08:00–09:00truefalseNo
    09:30–10:30truetrueYes
    10:00–11:00falsetrueNo
    08:30–11:00truetrueYes

    Booking ranges are half-open: they include the start but not the end. A new booking that starts at 10:00, when another ends at 10:00, makes start < b.End false, so there is no clash. Overlapping times in different rooms are also allowed.

    The mistake to avoid. Do not use inclusive comparisons at both ends when the agreed rule allows adjacent bookings. That would reject a valid 10:00 start after a 10:00 end.

    In an interview, say: “I would agree on the public operations first, then build the smallest working path in memory. Here a booking is accepted only for a known room, a valid time range, an unused ID, and no same-room overlap. Adjacent bookings are allowed.”

    Driver and self-check: show it works before adding more

    Our driver is Demo.Main: it calls TryBook with sample inputs. A self-check compares the actual result with an expected result instead of making the interviewer inspect the output manually.

    Check.Equal prints PASS or FAIL using an ordinary method call. Do not use Debug.Assert for this: its calls are removed in Release builds, so the checks would silently disappear. Its purpose is modest: make the agreed behavior easy to demonstrate.

    The checks cover a successful booking, the exact time boundary, a conflict, room independence, and invalid requests.

    For a 90-minute round, use this starting plan:

    TimeWork
    About 10 minutesClarify users, requirements, limits, and assumptions
    About 15 minutesModel and cut; agree on the public API
    About 50 minutesBuild in memory, keeping a working path available
    About 10 minutesRun self-checks and demonstrate the behavior
    About 5 minutesKeep spare for mistakes or a small change

    Do not wait until the final ten minutes to run the program. Run a small path as soon as it exists.

    If only twenty minutes remain, stop adding good-to-haves. Finish the must-haves, make the driver reliable, and list unfinished work. If a must-have is at risk, say so immediately and agree on the remaining scope.

    When asked for a change, first state its expected behavior and add a check. For example, cancellation should release a booking's time slot. Then make the smallest necessary code change and rerun the existing checks.

    The mistake to avoid. Do not spend the last twenty minutes adding an elegant extra while the required booking path still fails. The interviewer needs working evidence, not only intentions.

    In an interview, say: “With twenty minutes left, I would finish the must-haves and the demo, run the boundary checks, and list the rest. I would tell you what remains rather than quietly leave required behavior unfinished.”

    Trade-offs: add an interface for a real change

    We deliberately have no booking-storage interface. The exercise asks for one in-memory implementation, and no current caller needs a substitute.

    An interface becomes useful when you can name the change it protects against. If the interviewer requires both in-memory storage and database storage, an interface for storage, often called a repository, could let the booking rules use either implementation. The cost is one more interface to design and keep up to date.

    Do not add a design pattern merely to show that you know its name. Start with a requirement, identify what varies, and decide whether an interface makes that variation easier to handle.

    There are other honest trade-offs in our example:

    • Returning bool keeps the API small, but the caller cannot distinguish a clash from an unknown room. Separate failure reasons would improve feedback.
    • Searching lists keeps the code short, but each TryBook scans every room and every booking: O(R + B). A dictionary keyed by booking ID makes the duplicate check O(1). Keeping each room's bookings sorted by start means the clash check only needs the bookings just before and after the new start.
    • In-memory storage keeps the demonstration simple, but accepted bookings do not survive a restart.

    The mistake to avoid. Do not defend an interface with “it follows SOLID.” Name a concrete substitution or change. If you cannot, consider removing it.

    In an interview, say: “I add an interface when I can name the change it protects against, such as switching between in-memory and database storage. This scope needs only one implementation, so I would keep the concrete class for now.”

    Check yourself

    You are about to design a meeting-room booker. What should you do first?

    A Add a repository interface and a notification interface, so storage can change later.
    B Agree on users, actions, limits, concurrency, storage and scope; write them down.
    C Choose the database and its tables first, because storage shapes every booking rule.
    D Draw every class a production booking system might need, so nothing is missed later.
    Show answer

    Correct answer: B

    These answers determine what the design must support. Classes and storage choices should follow the agreed requirements.

    A room is booked from 09:00 to 10:00. The agreed rule allows adjacent bookings. Which request must be rejected?

    A The same room from 09:30 to 10:30.
    B The same room from 10:00 to 11:00.
    C Another room from 09:30 to 10:30.
    D The same room from 08:00 to 09:00.
    Show answer

    Correct answer: A

    C overlaps an existing booking in the same room. A and D only meet a boundary. B uses a different room.

    Going deeper

    The example assumes calls happen one at a time. Without that assumption, two calls could both finish checking before either adds its booking. Both could then accept the same slot.

    Within one process, every caller must use the same lock around the complete check-and-add operation. See the C# lock statement. If the storage or deployment requirements change, revisit how conflicting bookings are prevented rather than assuming the current approach is enough.

    DateTime comparisons compare time values without resolving different time zones for you. The example avoids that issue by requiring all supplied times to use the same time zone. Microsoft's DateTime.Compare documentation explains the comparison behavior and the need to compare times on the same basis.

    Sources

    Sign in to mark lessons done and keep your place in the course.Sign in

    Checked before publishing: C# examples run on .NET 10, links opened, reviewed while it was written and read in full. How lessons are checked

    Updated 1 Dec 2026 ·