Library Management System

easy · CRUD + business rules

Brief-reported interview attribution (unverified): Amazon, Microsoft

How to approach an LLD round

Requirements

  • Functional: add books, register members, borrow (max 3 books, 14-day loan), return with a $1/day late fine, list available copies and a member's books, search by title.
  • Non-functional: the lending rules (limit, loan days, fine) must live in one place so they can change without touching the library; borrowing must not let a book's count go negative.
  • Out of scope: reservations, branches, fines payment, notifications.

Statement

Design a library. It tracks books (copies available), members, and loans. A member may borrow at most 3 books at a time, and may not borrow the same book twice. A loan lasts 14 days; returning late costs $1 per day over 14.

class Library:
    def __init__(self):
    def add_book(self, book_id, title, author, copies):
        # adding the same book_id again increases total and available copies
    def register_member(self, member_id, name):
        # registering the same member_id again is a no-op
    def borrow(self, member_id, book_id):
        # -> True if the loan is made, False otherwise
    def return_book(self, member_id, book_id, days_borrowed):
        # -> fine in dollars (int), or None if the member never borrowed that book
    def available_copies(self, book_id):
        # -> int (0 for an unknown book)
    def borrowed_books(self, member_id):
        # -> sorted list of book_ids the member currently has (empty for unknown member)
    def search_by_title(self, query):
        # -> sorted list of book_ids whose title contains the query (case-insensitive)

Rules. borrow returns False when the member or book is unknown, no copy is available, the member already has 3 books, or the member already has this book. return_book returns max(0, days_borrowed - 14) * 1.

Money units: late fees are whole dollars, not cents; six days late returns 6.

Tests use explicit inputs and injected clocks/callbacks. No network, real threads or application-server execution is involved.

Class design (SOLID)

Book (copies and availability; SRP). Member (borrowed set; SRP). LoanPolicy (ABC interface) + StandardLoanPolicy (max books, loan days, fine; OCP — change the rules by swapping the policy). Library orchestrates and takes the policy as a constructor argument (DIP). Pattern: Policy/Strategy (lending rules).

Public demo

# Public demo: run after implementing the class API above.
l = Library()
for bid, title, copies in [('B1', 'Python Crash Course', 1), ('B2', 'Fluent Python', 2), ('B3', 'Clean Code', 1), ('B4', 'Design Patterns', 1)]:
    l.add_book(bid, title, 'Author', copies)
l.register_member('M1', 'Asha')
l.register_member('M2', 'Ravi')
print(l.borrow('M1', 'B1'))
print(l.available_copies('B1'))

Reference solution and hidden tests

Locked. Open the interactive editor and attempt the problem; the reference, hidden test descriptions, pattern explanation and complexity are available only after an explicit reveal.

Concurrency

Two members borrowing the last copy must not both succeed. The availability check and the decrement must be atomic: one lock per book (or per library) around borrow/return. The reference is single-threaded; the lock is described here.

Trade-offs & extensions

Fines are computed from the days borrowed, passed in — the system does not track dates itself. Extending: a Loan object with due dates, an inverted token index for title search, a Reservation queue, and a NotificationService (Observer) for overdue books.

Starter code

from abc import ABC, abstractmethod

class Book:

    def __init__(self, title, author, copies):
        """Initialize the state described in the problem."""
        pass

    def add_copies(self, n):
        """Implement the return value and rules in the API contract."""
        pass

class Member:

    def __init__(self, name):
        """Initialize the state described in the problem."""
        pass

class LoanPolicy(ABC):

    @abstractmethod
    def can_borrow(self, member, book):
        """Implement the return value and rules in the API contract."""
        pass

    @abstractmethod
    def fine(self, days_borrowed):
        """Implement the return value and rules in the API contract."""
        pass

class StandardLoanPolicy(LoanPolicy):

    def can_borrow(self, member, book):
        """Implement the return value and rules in the API contract."""
        pass

    def fine(self, days_borrowed):
        """Implement the return value and rules in the API contract."""
        pass

class Library:

    def __init__(self, policy=None):
        """Initialize the state described in the problem."""
        pass

    def add_book(self, book_id, title, author, copies):
        """adding the same book_id again increases total and available copies"""
        pass

    def register_member(self, member_id, name):
        """registering the same member_id again is a no-op"""
        pass

    def borrow(self, member_id, book_id):
        """-> True if the loan is made, False otherwise"""
        pass

    def return_book(self, member_id, book_id, days_borrowed):
        """-> fine in dollars (int), or None if the member never borrowed that book"""
        pass

    def available_copies(self, book_id):
        """-> int (0 for an unknown book)"""
        pass

    def borrowed_books(self, member_id):
        """-> sorted list of book_ids the member currently has (empty for unknown member)"""
        pass

    def search_by_title(self, query):
        """-> sorted list of book_ids whose title contains the query (case-insensitive)"""
        pass
Loading editor…

Each test has a five-second execution limit. Your practice drafts and solved progress stay in this browser.

Return to the Python interpreter

4 comments

Seed comments are jokes from TryGetValue’s fictional characters, not real user posts.

Your posts stay in this browser, for this problem only. They are not shared with other visitors.

  1. AntyCharacter joke · No posting date

    I carried this test case uphill both ways. It still failed.

  2. InterviewerCharacter joke · No posting date

    Great approach. Now solve it without using the thing you just used.

  3. AntyCharacter joke · No posting date

    This problem has 8 hidden tests. I found 9 ways to fail them.

  4. The GraderCharacter joke · No posting date

    Edge case? Never met her.