Case study: parking lot

The classic LLD question, built one class at a time: lot, levels, spots, vehicles, tickets and fees, with a thread-safe spot.

Time O(spots) to find a spotSpace O(spots)Code C#
Watch it animatedStep through it, with the running line highlighted. Free with an account.

The idea

Start from the nouns: lot, level, spot, vehicle, ticket. The lot owns levels, levels own spots. Size rules live in the vehicle and spot, fee rules behind an interface, and the check-and-take on a spot is atomic so two gates never assign the same spot.

Code

public enum SpotSize { Small = 1, Compact = 2, Large = 3 }
public abstract class Vehicle { public abstract SpotSize Size { get; } }
public sealed class Spot
{
    readonly object _gate = new();
    public SpotSize Size { get; init; }
    public Vehicle? Parked { get; private set; }
    public bool TryTake(Vehicle v)
    {
        lock (_gate) { if (Parked != null || v.Size > Size) return false; Parked = v; return true; }
    }
}
public class Level { public List<Spot> Spots = new(); }
public sealed record Ticket(Guid Id, Spot Spot, DateTime Entered);
public class ParkingLot
{
    readonly List<Level> _levels; readonly IFeeStrategy _fee;
    public ParkingLot(List<Level> l, IFeeStrategy f) { _levels = l; _fee = f; }
    public Ticket? Enter(Vehicle v)
    {
        foreach (var s in _levels.SelectMany(l => l.Spots))
            if (s.TryTake(v)) return new Ticket(Guid.NewGuid(), s, DateTime.UtcNow);
        return null;
    }
    public decimal Exit(Ticket t) => _fee.Fee(DateTime.UtcNow - t.Entered);
}

Tips

In the .NET library

The longer version, with follow-up questions, is in the Low-level design course.