LOW LEVEL DESIGN · MACHINE CODING · MEDIUM · 12 OF 42

Design a Vehicle Rental System: LLD in Java

A car rental system designed and coded: branches, vehicle types, half-open time ranges, a booking calendar per vehicle with a TreeMap neighbour check, search by availability, booking without double booking, pricing as a Strategy with a discount Decorator, a booking state machine, late and damage fees at return, and the follow-ups, with a full Java 17 solution.

Patterns usedDecoratorStrategyState

  1. 1
  2. 2
  3. 3
  4. 4
  5. 5
  6. 6
  7. 7
  8. 8
  9. 9
  10. 10
  11. 11
  12. 12
  13. 13
  14. 14
  15. 15
  16. 16
  17. 17
  18. 18
  19. 19
  20. 20
  21. 21
  22. 22
  23. 23
  24. 24
  25. 25
  26. 26
  27. 27
  28. 28
  29. 29
  30. 30
  31. 31
  32. 32
  33. 33
  34. 34
  35. 35
  36. 36
  37. 37
  38. 38
  39. 39
  40. 40
  41. 41
  42. 42
1 / 19

Press play to hear the narration, or step through at your own pace. The full Java code is below.

Full Java solution

One file, Java 17, 291 lines, with a small main() demo. Save it as VehicleRental.java, then run javac VehicleRental.java && java VehicleRental.

import java.time.Duration;
import java.time.Instant;
import java.util.ArrayList;
import java.util.EnumMap;
import java.util.List;
import java.util.Map;
import java.util.NavigableMap;
import java.util.TreeMap;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.CopyOnWriteArrayList;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicInteger;
import java.util.concurrent.atomic.AtomicLong;

/** Vehicle rental: branches hold vehicles, each vehicle keeps its own calendar, pricing is a strategy. */
public class VehicleRental {

    // ---------- the model ----------
    enum VehicleType { HATCHBACK, SEDAN, SUV }

    enum BookingStatus { BOOKED, PICKED_UP, RETURNED, CANCELLED }

    /** Half-open range [start, end): a booking ending at 10:00 does not clash with one starting at 10:00. */
    record TimeRange(Instant start, Instant end) {
        TimeRange {
            if (!end.isAfter(start)) throw new IllegalArgumentException("end must be after start");
        }

        boolean overlaps(TimeRange o) { return start.isBefore(o.end) && o.start.isBefore(end); }

        long startedDays() { return (Duration.between(start, end).toMinutes() + 1439) / 1440; }
    }

    record Customer(String id, String name) {}

    record Branch(String id, String city) {}

    record Charge(String label, long cents) {}

    record Invoice(String bookingId, long rentCents, List<Charge> extras) {
        long total() { return rentCents + extras.stream().mapToLong(Charge::cents).sum(); }

        long extra(String label) {
            return extras.stream().filter(c -> c.label().equals(label)).mapToLong(Charge::cents).sum();
        }
    }

    static final class Booking {
        final String id;
        final Customer customer;
        final Vehicle vehicle;
        final TimeRange range;
        final long quotedCents;
        BookingStatus status = BookingStatus.BOOKED; // guarded by the vehicle's lock

        Booking(String id, Customer c, Vehicle v, TimeRange r, long quoted) {
            this.id = id;
            this.customer = c;
            this.vehicle = v;
            this.range = r;
            this.quotedCents = quoted;
        }
    }

    /** A vehicle owns its calendar. Booking checks and inserts under the vehicle's own lock. */
    static final class Vehicle {
        final String id;
        final VehicleType type;
        final Branch branch;
        private final NavigableMap<Instant, Booking> calendar = new TreeMap<>(); // keyed by start

        Vehicle(String id, VehicleType type, Branch branch) {
            this.id = id;
            this.type = type;
            this.branch = branch;
        }

        /** Only neighbours can clash: the booking that starts just before, and the one that starts next. */
        synchronized boolean isFree(TimeRange r) {
            Map.Entry<Instant, Booking> before = calendar.floorEntry(r.start());
            if (before != null && before.getValue().range.overlaps(r)) return false;
            Map.Entry<Instant, Booking> after = calendar.higherEntry(r.start());
            return after == null || !after.getValue().range.overlaps(r);
        }

        /** Check-then-insert as one atomic step, so two customers cannot both get this car. */
        synchronized boolean tryReserve(Booking b) {
            if (!isFree(b.range)) return false;
            calendar.put(b.range.start(), b);
            return true;
        }

        synchronized void release(Booking b) { calendar.remove(b.range.start(), b); }
    }

    // ---------- strategies ----------
    interface PricingStrategy { long quote(VehicleType type, TimeRange r); }

    /** Charge per started day with a rate per vehicle type. */
    record DailyPricing(Map<VehicleType, Long> perDay) implements PricingStrategy {
        public long quote(VehicleType type, TimeRange r) { return r.startedDays() * perDay.get(type); }
    }

    /** Decorator: wraps any pricing and takes a percentage off long rentals. */
    record LongRentalDiscount(PricingStrategy inner, int minDays, int percentOff) implements PricingStrategy {
        public long quote(VehicleType type, TimeRange r) {
            long base = inner.quote(type, r);
            return r.startedDays() >= minDays ? base * (100 - percentOff) / 100 : base;
        }
    }

    /** Extra charges at return time: each rule is a class, the invoice sums them. */
    interface ReturnFee { Charge fee(Booking b, Instant returnedAt, boolean damaged); }

    record LateFee(Map<VehicleType, Long> perHour) implements ReturnFee {
        public Charge fee(Booking b, Instant at, boolean damaged) {
            long lateMin = Duration.between(b.range.end(), at).toMinutes();
            return new Charge("late", lateMin <= 0 ? 0 : ((lateMin + 59) / 60) * perHour.get(b.vehicle.type));
        }
    }

    record DamageFee(long flatCents) implements ReturnFee {
        public Charge fee(Booking b, Instant at, boolean damaged) {
            return new Charge("damage", damaged ? flatCents : 0);
        }
    }

    // ---------- the service ----------
    private final Map<String, List<Vehicle>> fleetByBranch = new ConcurrentHashMap<>();
    private final Map<String, Booking> bookings = new ConcurrentHashMap<>();
    private final AtomicLong seq = new AtomicLong();
    private final PricingStrategy pricing;
    private final List<ReturnFee> fees;

    VehicleRental(PricingStrategy pricing, List<ReturnFee> fees) {
        this.pricing = pricing;
        this.fees = List.copyOf(fees);
    }

    void addVehicle(Vehicle v) {
        fleetByBranch.computeIfAbsent(v.branch.id(), k -> new CopyOnWriteArrayList<>()).add(v);
    }

    /** Search: vehicles of a type at a branch that are free for the whole range. */
    List<Vehicle> search(String branchId, VehicleType type, TimeRange r) {
        List<Vehicle> out = new ArrayList<>();
        for (Vehicle v : fleetByBranch.getOrDefault(branchId, List.of()))
            if (v.type == type && v.isFree(r)) out.add(v);
        return out;
    }

    /** Book any free vehicle of the type: try candidates until one reservation sticks. */
    Booking book(Customer c, String branchId, VehicleType type, TimeRange r) {
        long quote = pricing.quote(type, r);
        for (Vehicle v : search(branchId, type, r)) {
            Booking b = new Booking("B" + seq.incrementAndGet(), c, v, r, quote);
            if (v.tryReserve(b)) { // lost a race? the next candidate is tried
                bookings.put(b.id, b);
                return b;
            }
        }
        throw new IllegalStateException("no " + type + " free at " + branchId);
    }

    void pickUp(String bookingId) { transition(bookingId, BookingStatus.BOOKED, BookingStatus.PICKED_UP); }

    void cancel(String bookingId) {
        Booking b = transition(bookingId, BookingStatus.BOOKED, BookingStatus.CANCELLED);
        b.vehicle.release(b);
    }

    Invoice returnVehicle(String bookingId, Instant at, boolean damaged) {
        Booking b = transition(bookingId, BookingStatus.PICKED_UP, BookingStatus.RETURNED);
        List<Charge> extras = new ArrayList<>();
        for (ReturnFee f : fees) {
            Charge c = f.fee(b, at, damaged);
            if (c.cents() > 0) extras.add(c);
        }
        return new Invoice(b.id, b.quotedCents, extras);
    }

    /** Status changes go through one method: an illegal jump (return before pick-up) is rejected. */
    private Booking transition(String id, BookingStatus from, BookingStatus to) {
        Booking b = bookings.get(id);
        if (b == null) throw new IllegalArgumentException("unknown booking " + id);
        synchronized (b.vehicle) {
            if (b.status != from) throw new IllegalStateException(id + " is " + b.status + ", not " + from);
            b.status = to;
        }
        return b;
    }

    // ---------- demo ----------
    static TimeRange range(String from, String to) {
        return new TimeRange(Instant.parse(from + ":00Z"), Instant.parse(to + ":00Z"));
    }

    static String money(long cents) { return String.format("%.2f", cents / 100.0); }

    static void check(boolean ok, String what) {
        if (!ok) throw new AssertionError(what);
    }

    public static void main(String[] args) throws InterruptedException {
        Map<VehicleType, Long> perDay = new EnumMap<>(VehicleType.class);
        perDay.put(VehicleType.HATCHBACK, 180000L);
        perDay.put(VehicleType.SEDAN, 250000L);
        perDay.put(VehicleType.SUV, 400000L);
        Map<VehicleType, Long> latePerHour = new EnumMap<>(VehicleType.class);
        perDay.forEach((t, d) -> latePerHour.put(t, d / 10));
        VehicleRental rental = new VehicleRental(new LongRentalDiscount(new DailyPricing(perDay), 7, 10),
                List.of(new LateFee(latePerHour), new DamageFee(500000L)));
        Branch airport = new Branch("AIRPORT", "Metro"), downtown = new Branch("DOWNTOWN", "Metro");
        rental.addVehicle(new Vehicle("SED-1", VehicleType.SEDAN, airport));
        rental.addVehicle(new Vehicle("SED-2", VehicleType.SEDAN, airport));
        rental.addVehicle(new Vehicle("SUV-1", VehicleType.SUV, airport));
        rental.addVehicle(new Vehicle("HAT-1", VehicleType.HATCHBACK, downtown));
        Customer traveller = new Customer("C1", "Traveller"), tourist = new Customer("C2", "Tourist");

        TimeRange mon = range("2026-03-02T10:00", "2026-03-04T10:00");
        Booking b1 = rental.book(traveller, "AIRPORT", VehicleType.SEDAN, mon);
        System.out.println(b1.id + ": " + b1.vehicle.id + " for 2 days, quote " + money(b1.quotedCents));
        TimeRange overlap = range("2026-03-03T09:00", "2026-03-05T09:00");
        int free = rental.search("AIRPORT", VehicleType.SEDAN, overlap).size();
        System.out.println("Sedans free on the overlap: " + free);
        Booking b2 = rental.book(tourist, "AIRPORT", VehicleType.SEDAN, overlap);
        System.out.println(b2.id + ": " + b2.vehicle.id);
        try {
            rental.book(new Customer("C3", "Visitor"), "AIRPORT", VehicleType.SEDAN, overlap);
            throw new AssertionError("third sedan booked");
        } catch (IllegalStateException e) {
            System.out.println("Third request: " + e.getMessage());
        }
        TimeRange touching = range("2026-03-04T10:00", "2026-03-05T10:00");
        check(rental.search("AIRPORT", VehicleType.SEDAN, touching).size() == 1, "back-to-back allowed");
        System.out.println("Back-to-back from 10:00 Wed: SED-1 free");

        TimeRange week = range("2026-03-10T08:00", "2026-03-17T08:00");
        Booking b3 = rental.book(tourist, "DOWNTOWN", VehicleType.HATCHBACK, week);
        System.out.println(b3.id + ": 7 days hatchback, 10% off, quote " + money(b3.quotedCents));
        check(b3.quotedCents == 7 * 180000L * 90 / 100, "long rental discount");

        rental.pickUp(b1.id);
        Invoice inv = rental.returnVehicle(b1.id, mon.end().plus(Duration.ofMinutes(170)), false);
        System.out.println("Return 2h50m late: rent " + money(inv.rentCents()) + " + late "
                + money(inv.extra("late")) + " = " + money(inv.total()));
        check(inv.extra("late") == 3 * 25000L, "three started hours late");
        try {
            rental.returnVehicle(b2.id, overlap.end(), false);
            throw new AssertionError("returned before pick-up");
        } catch (IllegalStateException e) {
            System.out.println("Rejected: " + e.getMessage());
        }
        rental.cancel(b2.id);
        check(rental.search("AIRPORT", VehicleType.SEDAN, overlap).size() == 1, "cancel frees the car");
        System.out.println("Cancelled " + b2.id + ": SED-2 free again");
        rental.pickUp(b3.id);
        Invoice dented = rental.returnVehicle(b3.id, week.end().minus(Duration.ofHours(5)), true);
        System.out.println("Hatchback back early with a dent: damage " + money(dented.extra("damage"))
                + ", total " + money(dented.total()));
        check(dented.extra("late") == 0 && dented.extra("damage") == 500000L, "damage only");

        // Twelve customers race for the one SUV on the same dates: exactly one wins.
        TimeRange weekend = range("2026-03-07T09:00", "2026-03-08T21:00");
        AtomicInteger won = new AtomicInteger(), lost = new AtomicInteger();
        CountDownLatch go = new CountDownLatch(1);
        ExecutorService pool = Executors.newFixedThreadPool(12);
        for (int i = 0; i < 12; i++) {
            Customer c = new Customer("R" + i, "Racer" + i);
            pool.submit(() -> {
                try {
                    go.await();
                    rental.book(c, "AIRPORT", VehicleType.SUV, weekend);
                    won.incrementAndGet();
                } catch (IllegalStateException e) {
                    lost.incrementAndGet();
                } catch (InterruptedException e) {
                    Thread.currentThread().interrupt();
                }
            });
        }
        go.countDown();
        pool.shutdown();
        check(pool.awaitTermination(5, TimeUnit.SECONDS), "pool did not finish");
        System.out.println("SUV race: " + won.get() + " booked, " + lost.get() + " turned away");
        check(won.get() == 1, "double booking");
    }
}

Notes

Requirements

The requirements. The company has branches, each with a fleet of hatchbacks, sedans and SUVs. A customer searches by branch, type and a time range, and books any free vehicle of that type. Bookings can be picked up, returned or cancelled. Price is per day by type, long rentals get a discount, and returns can add late and damage fees. Many customers book at the same time. Payments and identity checks are out of scope.

Clarify the time rules, because they decide the data structures. Customers book a type, not a specific car, and the system picks one. If one rental ends at ten and the next starts at ten, that is allowed, which tells us ranges are half-open. A day is every started twenty four hours. Late returns are charged per started hour. Returning to a different branch is a later extension with a one-way fee.

Requirements
  • branches, each with a fleet
  • types: hatchback, sedan, SUV
  • search: type + branch + dates
  • book any free vehicle of a type
  • pick up, return, cancel
  • price per day by type
  • long rentals get a discount
  • late return and damage fees
  • many customers book at once
  • out of scope: payments, KYC
Clarify first
  • book a type or a specific car?
  • a type; we pick the car
  • return at 10:00, next pickup
  • at 10:00: allowed? yes
  • how is a day counted?
  • every started 24 hours
  • late fee?
  • per started hour, by type
  • return to another branch?
  • extension, one-way fee

Entities

The entities. The service has branches, and each branch has vehicles. A booking ties a customer to one vehicle for one time range, with a price quoted at booking time and a status. The time range deserves its own type, because the overlap rule is subtle and should live in exactly one place. Invoices appear at return time.

Class diagram

In code, kinds and states are enums: vehicle type and booking status. Values that never change are records: the time range, customer, branch, a charge and the invoice. Two classes hold changing state. A vehicle owns its calendar of bookings, and a booking has a status that moves through its lifecycle. Money is a long count of paise, never a double.

Types
enum VehicleType { HATCHBACK, SEDAN, SUV }
enum BookingStatus { BOOKED, PICKED_UP,
                     RETURNED, CANCELLED }
record TimeRange(Instant start, Instant end)
record Customer(String id, String name)
record Branch(String id, String city)
record Charge(String label, long cents)
record Invoice(id, rentCents, extras)
class Vehicle  { id, type, calendar }
class Booking  { ..., status }

Time ranges

The overlap rule is one line, but it is where bugs hide. Treat a range as half-open: it includes the start but not the end. Two ranges overlap when each starts before the other ends. So a rental ending Wednesday at ten and the next starting Wednesday at ten do not clash, while Tuesday to Thursday does. The record's constructor also rejects a range whose end is not after its start.

TimeRange.overlaps()
// [start, end): end is not included
boolean overlaps(TimeRange o) {
  return start.isBefore(o.end)
      && o.start.isBefore(end);
}

Mon 10:00 to Wed 10:00
Wed 10:00 to Thu 10:00: no clash
Tue 09:00 to Thu 09:00: clash
constructor rejects end <= start

Calendar per vehicle

Each vehicle keeps its bookings in a tree map sorted by start time. Because a vehicle's bookings never overlap each other, only two can possibly clash with a new range: the one that starts at or just before it, and the next one after. Floor entry and higher entry find both in logarithmic time. That beats scanning a list of every booking the car ever had, and it is a detail interviewers notice.

isFree(range)
TreeMap<Instant, Booking> calendar

before = calendar.floorEntry(r.start)
if before overlaps r: busy
after = calendar.higherEntry(r.start)
if after overlaps r: busy
otherwise free

O(log n) per vehicle, not a scan
bookings never overlap each other

Flow: search

Search is a filter. Take the fleet at the branch, keep vehicles of the requested type, and ask each vehicle's calendar whether the range is free. With two sedans at the airport and one already booked from Monday to Wednesday, a search for Tuesday to Thursday returns exactly one. For a big fleet you would index vehicles by branch and type so the filter only touches candidates.

search(branch, type, range)
for (Vehicle v : fleetByBranch(b))
  if (v.type == type
      && v.isFree(range)) out.add(v)
return out

two sedans at the airport,
  one booked Mon to Wed
search Tue to Thu: 1 free

Flow: book

Booking quotes the price, then walks the search results. For each candidate it tries to reserve the booking on that vehicle. Search ran without a lock, so the car may have been taken a moment ago; if the reservation fails, move on to the next candidate. The first success is stored and returned. If every candidate fails, the customer gets a clear no-availability error.

book(customer, branch, type, r)
quote = pricing.quote(type, r)
for (Vehicle v : search(branch, type, r))
  b = new Booking(id, c, v, r, quote)
  if (v.tryReserve(b)) {
    bookings.put(b.id, b)
    return b
  }
  // lost a race: try the next one
throw: no free vehicle of this type

Strategy + Decorator

Pricing is a strategy: daily pricing multiplies started days by a rate per type. Discounts are a decorator: a long rental discount wraps any pricing strategy, asks it for the base price, and takes ten percent off for seven days or more. Weekend surcharges, coupons or a loyalty discount are more decorators stacked the same way, and the service never changes. A seven day hatchback comes to eleven thousand three hundred and forty.

Pricing
interface PricingStrategy {
  long quote(VehicleType t, TimeRange r);
}
DailyPricing: startedDays x rate[type]
LongRentalDiscount(inner, 7 days, 10%)
  base = inner.quote(t, r)
  days >= 7 ? base x 90 / 100 : base

hatchback, 7 days at 1800.00
  12600.00 less 10% = 11340.00

State machine

A booking is a small state machine. Booked can move to picked up or cancelled, and picked up can move to returned. Every change goes through one transition method that checks the current state under the vehicle's lock. So returning a car that was never picked up is rejected with a clear message, and cancelling removes the booking from the calendar so the car is free again.

Booking lifecycle
BOOKED -> PICKED_UP -> RETURNED
BOOKED -> CANCELLED (frees the car)

transition(id, from, to):
  synchronized (vehicle) {
    if (status != from) throw
    status = to
  }
return before pick-up: rejected

Flow: return

On return, move the booking to returned, then run a list of fee rules. Each rule is a small class that returns a labelled charge: the late fee charges every started hour past the end at a rate per type, the damage fee adds a flat amount. The invoice keeps the quoted rent plus whichever charges applied. Two hours fifty late on a sedan is three started hours, seven hundred and fifty extra.

returnVehicle(id, at, damaged)
b = transition(id, PICKED_UP, RETURNED)
for (ReturnFee f : fees)
  c = f.fee(b, at, damaged)
  if (c.cents > 0) extras.add(c)
return new Invoice(id, quote, extras)

LateFee: started hours x rate[type]
DamageFee: flat amount if damaged
fuel, cleaning, tolls: new classes

Concurrency

Now the race. Twelve customers search at once and all see the one SUV as free. If booking were check, then insert, several would win. So checking the calendar and inserting the booking happen inside one synchronized method on that vehicle. Exactly one customer gets the SUV and the rest are told it is gone. The lock is per vehicle, so bookings for other cars never wait.

Give every shared field a safe home. The calendar is a plain tree map that is only touched under its vehicle's lock, and status changes use the same lock. The fleet and the bookings sit in concurrent maps and lists, ids come from an atomic counter, and records are immutable. In a real database the same guarantee comes from an exclusion constraint that forbids two overlapping ranges for one car.

No double booking
synchronized boolean tryReserve(b) {
  if (!isFree(b.range)) return false;
  calendar.put(b.range.start, b);
  return true;
}

check and insert under one lock
lock per vehicle: other cars and
  other branches never wait
12 racers, 1 SUV: 1 booked, 11 not
Thread safety checklist
  • calendar: TreeMap, only touched
  • under the vehicle lock
  • status: changed under the
  • same vehicle lock
  • fleet: ConcurrentHashMap of
  • CopyOnWriteArrayList
  • bookings: ConcurrentHashMap
  • ids: AtomicLong
  • records: immutable, shareable
  • in a database: an exclusion
  • constraint on (car, range)

Extensibility

Extensions slot in cleanly. A one-way rental records the return branch, moves the car to that fleet and adds a fee. A cleaning buffer pads each range by an hour inside the free check. Weekend surcharges and coupons are more pricing decorators, and fuel or toll charges are more return fees. Picking a specific car or features like automatic transmission is an extra search filter.

Extension points
  • one-way rental: a return branch,
  • the car moves fleets, a fee
  • cleaning buffer: pad each range
  • by an hour in isFree()
  • weekend surcharge, coupons:
  • more pricing decorators
  • fuel and tolls: more ReturnFees
  • specific car or features:
  • filter in search()
  • loyalty tiers: a Customer field

Testing

The full code is below the player. The demo books two sedans and is refused a third on overlapping dates, proves a back-to-back booking at ten on Wednesday is allowed, applies the long rental discount, charges a late return by started hours, rejects a return before pick-up, frees a car on cancel, adds a damage fee, and finally races twelve customers for one SUV. Exactly one wins, every time.

Run it
B1: SED-1 for 2 days, quote 5000.00
Sedans free on the overlap: 1
Third request: no SEDAN free at AIRPORT
Back-to-back from 10:00 Wed: SED-1 free
B3: 7 days hatchback, 10% off,
  quote 11340.00
Return 2h50m late: rent 5000.00
  + late 750.00 = 5750.00
Rejected: B2 is BOOKED, not PICKED_UP
SUV race: 1 booked, 11 turned away

Follow-ups

Expect follow-ups. Why half-open ranges? Back-to-back rentals do not clash. Why a tree map? Only two neighbours can overlap, found in log time. What if a customer is late and the next booking is about to start? Reassign the next booking to another car of the same type. Holding a car during payment is a pending booking with a short expiry. And in SQL, use an exclusion constraint or lock the car's row while inserting.

Follow-ups to expect
  • why half-open ranges?
  • why a TreeMap per vehicle?
  • customer is late and the next
  • booking starts: swap the car
  • hold a car while paying?
  • BOOKED with a 10 min expiry
  • search across many branches?
  • index by city, then branch
  • store it in SQL? exclusion
  • constraint or row lock per car

Say it like this

The short version. Each vehicle owns a calendar of half-open ranges in a tree map, so only two neighbours can ever clash with a new booking. Reserving checks and inserts under that vehicle's lock, so no car is booked twice. Pricing is a strategy wrapped by discount decorators, return fees are a list of rules, and bookings move through a checked state machine.

In the interview
  • "Each vehicle owns a TreeMap
  • calendar of half-open ranges;
  • only two neighbours can clash.
  • Reserving checks and inserts
  • under the vehicle lock. Pricing
  • is a strategy with discount
  • decorators, fees at return are
  • a list of rules, and bookings
  • are a checked state machine."

Interview questions

How do you check whether a vehicle is free for a time range?

Keep the vehicle's bookings in a TreeMap keyed by start time. Because bookings never overlap each other, only floorEntry(start) and higherEntry(start) can clash with the new range, so the check is O(log n) instead of a scan.

Why use half-open time ranges?

With [start, end) a rental ending at 10:00 and another starting at 10:00 do not overlap, which matches how rentals work. The overlap test becomes a simple pair of comparisons: a.start < b.end and b.start < a.end.

How do you prevent two customers booking the same car?

Checking the calendar and inserting the booking happen together inside a method synchronized on that vehicle. Search runs without the lock, so book() tries each candidate and moves on if the reservation fails. In a database an exclusion constraint on (car, range) gives the same guarantee.

How is pricing designed to change easily?

A PricingStrategy interface with DailyPricing as the base, and discounts or surcharges as decorators that wrap another strategy. New offers are new classes stacked at configuration time; the rental service does not change.

How do you compute charges when a car is returned?

Run a list of ReturnFee rules, each returning a labelled Charge: late fee per started hour by type, damage fee, fuel, tolls. The invoice holds the quoted rent plus the charges that applied, which keeps each rule testable on its own.

How do you stop invalid booking state changes?

Model the lifecycle as a state machine and route every change through transition(id, expectedFrom, to) under the vehicle lock. Returning before pick-up or cancelling after pick-up fails with a clear error.

What if a customer returns late and the car is booked next?

Detect the conflict at return or when the car is overdue, and reassign the next booking to another free vehicle of the same type at that branch, upgrading if none is free. A cleaning buffer between bookings reduces how often this happens.

How would search scale to a large fleet?

Index vehicles by branch and type so a search touches only candidates, and keep each calendar as a sorted structure. For many cities, shard by city; availability can be cached per day and recomputed when a booking changes.