Bird
Raised Fist0

Library Management System

LLDmediumInterview freq: medium
Choose your preparation mode4 modes available
🏗️
Library Management System
Manage books, members, due dates, fines, and reservations efficiently
mediumLibrary and Catalog SystemsFreq: medium
Prerequisites:OOP DesignSOLID PrinciplesJava Concurrency Basics
⚙️
Functional Requirements
  • Allow members to borrow available books
  • Track due dates for borrowed books
  • Calculate fines for overdue returns
  • Allow members to reserve books currently lent out
  • Prevent multiple members from borrowing the same book copy simultaneously
  • Allow librarians to add or remove books from the catalog
  • Notify members when reserved books become available
👤
Use Cases
  • Member searches for books
  • Member borrows a book
  • Member returns a book
  • Member reserves a book
  • Librarian adds/removes books
  • System calculates fines for overdue books
🧑‍💻
Actors
  • Member
  • Librarian
  • System Administrator
❓
Clarifying Questions to Ask
  • How many concurrent users (threads) are expected to borrow or reserve books simultaneously?
  • Is there a pricing or fine calculation strategy that varies by member type or book category?
  • What should happen if a member tries to borrow a book that is reserved by another member?
  • Are partial reservations (e.g., for multiple copies) supported?
  • Should the system support multiple copies of the same book title?
Out of Scope
✗ Digital book lending
✗ Payment processing for fines
✗ Detailed search engine implementation
⚡
QPS Calculation
read qps500
write qps100
🖥️
Server Estimate
app servers5
db servers3
🔢
Enumerations
enum BookStatus
AVAILABLE | BORROWED | RESERVED | LOST
Enum prevents typo bugs and enables exhaustive switch statements for book lifecycle states.
enum MemberType
STUDENT | FACULTY | GUEST
Defines member categories to apply different borrowing limits and fine policies, enforcing type safety.
enum ReservationStatus
ACTIVE | FULFILLED | CANCELLED
Tracks reservation lifecycle explicitly to manage state transitions and notifications.
📦
Book
4 fields
private final String isbnprivate final String titleprivate final String authorprivate final int publicationYear
Represents a book title with immutable bibliographic data.
public String getIsbn()Returns the ISBN of the book.
public String getTitle()Returns the title of the book.
📦
BookCopy
4 fields
private final String copyIdprivate volatile BookStatus statusprivate volatile Member currentHolderprivate volatile LocalDate dueDate
Represents a physical copy of a book, tracks its status, current holder, and due date.
public synchronized boolean borrowCopy(Member member, LocalDate dueDate)Atomically checks availability and assigns the copy to the member with a due date.
public synchronized void returnCopy()Marks the copy as available and clears holder and due date.
public synchronized boolean reserveCopy(Member member)Atomically reserves the copy if available or borrowed.
📦
Member
6 fields
private final String memberIdprivate final String nameprivate final MemberType memberTypeprivate final List<BookCopy> borrowedCopiesprivate final List<Reservation> reservationsprivate volatile double outstandingFines
Represents a library member with borrowing and reservation records and fine tracking.
public synchronized boolean borrowBookCopy(BookCopy copy, LocalDate dueDate)Attempts to borrow a book copy, updating borrowedCopies and handling concurrency.
public synchronized void returnBookCopy(BookCopy copy)Returns a borrowed copy and updates fines if overdue.
public synchronized void addFine(double amount)Atomically adds to the member's outstanding fines.
📦
Reservation
5 fields
private final String reservationIdprivate final Member memberprivate final BookCopy bookCopyprivate volatile ReservationStatus statusprivate final LocalDate reservationDate
Tracks a member's reservation for a specific book copy and its status.
public synchronized void fulfillReservation()Marks the reservation as fulfilled when the book copy becomes available.
public synchronized void cancelReservation()Cancels the reservation and updates status.
📦
FinePolicy
1 fields
private final Map<MemberType, Double> finePerDay
Defines fine calculation rules per member type.
public double calculateFine(MemberType memberType, long overdueDays)Calculates fine based on member type and overdue days.
📦
LibraryCatalog
1 fields
private final Map<String, List<BookCopy>> bookCopiesByIsbn
Manages collections of book copies indexed by ISBN.
public synchronized void addBookCopy(BookCopy copy)Adds a new book copy to the catalog.
public synchronized boolean removeBookCopy(String copyId)Removes a book copy if not borrowed or reserved.
public List<BookCopy> searchByIsbn(String isbn)Returns list of book copies for given ISBN.
🔗
Relationships
LibraryCatalog◆──►BookCopy[1..*]
compositionLibraryCatalog owns BookCopies; copies cannot exist independently
Member──►BookCopy[0..*]
associationMember borrows BookCopies but copies exist independently
Reservation◇──►Member[1]
aggregationReservation references Member; Member can exist independently
Reservation◇──►BookCopy[1]
aggregationReservation references BookCopy; BookCopy exists independently
Member◆──►Reservation[0..*]
compositionMember owns Reservations; reservations deleted if member removed
🗄️
BookCopies
PK: isbn
copyId STRINGisbn STRINGstatus STRINGcurrentHolderId STRINGdueDate DATE
Stores physical copies of books with status and holder info.
🗄️
Members
PK: memberId
memberId STRINGname STRINGmemberType STRINGoutstandingFines DOUBLE
Stores member details and fine info.
🔌
borrowBookCopy
Request
{
  "memberId": "STRING",
  "copyId": "STRING",
  "dueDate": "DATE"
}
Response
{
  "success": "BOOLEAN",
  "message": "STRING"
}
Allows a member to borrow an available book copy.
🔌
returnBookCopy
Request
{
  "memberId": "STRING",
  "copyId": "STRING"
}
Response
{
  "success": "BOOLEAN",
  "message": "STRING",
  "fineCharged": "DOUBLE"
}
Processes return and calculates fines if overdue.
🔌
reserveBookCopy
Request
{
  "memberId": "STRING",
  "copyId": "STRING"
}
Response
{
  "success": "BOOLEAN",
  "message": "STRING"
}
Allows a member to reserve a book copy.

Practice

(1/5)
1. In designing the Amazon Locker Service, should the Package entity be modeled as an abstract class or an interface, and why?
easy
A. Abstract class, because interfaces cannot have any methods related to package handling.
B. Abstract class, because Package has shared state like tracking info and common behavior.
C. Interface, because Package only defines behaviors and allows multiple inheritance of behavior.
D. Interface, because Package needs to hold mutable state for OTP and expiry.

Solution

  1. Step 1: Analyze Package state and behavior

    Package has shared mutable state such as OTP, expiry time, and tracking info, which requires fields and common method implementations.
  2. Step 2: Abstract class vs interface suitability

    Abstract classes can hold state and provide default behavior, interfaces cannot hold mutable state (prior to Java 8 default methods, but still no fields). Therefore, abstract class fits better.
  3. Final Answer:

    Option B -> Option B
  4. Quick Check:

    Shared mutable state -> abstract class needed [check]
Hint: Stateful entities -> abstract class; stateless behaviors -> interface [check]
Common Mistakes:
2. In a parking system, should Vehicle be an abstract class or an interface if it needs to hold state like licensePlate and provide default behavior for getSize()? Why?
easy
A. Abstract class, because it can hold instance variables and provide default method implementations.
B. Abstract class, but only if it has no state to avoid violating interface segregation.
C. Interface, because state should always be in separate classes to keep interfaces clean.
D. Interface, because it allows multiple inheritance and default methods can hold state.

Solution

  1. Step 1: Analyze state and behavior requirements

    Vehicle needs to hold licensePlate (state) and provide default getSize() behavior, which interfaces cannot hold as instance variables.
  2. Step 2: Choose correct OOP construct

    Abstract classes can hold state and provide default implementations, interfaces cannot hold instance state (only constants).
  3. Final Answer:

    Option A -> Option A
  4. Quick Check:

    State + default behavior -> abstract class, not interface [check]
Hint: State needs abstract class; interfaces can't hold instance variables [check]
Common Mistakes:
3. You want to add a WeekendFeeStrategy to the rate limiter's fee calculation without modifying existing classes. Which SOLID principle applies and what is the minimum change?
medium
A. Add weekend flag to RateLimiter and use if-else inside existing fee method
B. Create new WeekendFeeStrategy implementing FeeStrategy interface; inject it via constructor (OCP and DIP enforced)
C. Modify RateLimiter class to add weekend fee logic directly, violating OCP
D. Create WeekendFeeStrategy but modify existing FeeStrategy implementations to handle weekend

Solution

  1. Step 1: Identify SOLID principle for adding new fee logic

    Open-Closed Principle (OCP) requires adding new behavior without modifying existing code.
  2. Step 2: Evaluate options for minimal change respecting OCP and DIP

    Add weekend flag to RateLimiter and use if-else inside existing fee method adds weekend flag and if-else inside existing method, violating OCP by modifying existing class. Create new WeekendFeeStrategy implementing FeeStrategy interface; inject it via constructor (OCP and DIP enforced) respects OCP and DIP by adding new class and injecting it.
  3. Final Answer:

    Option A -> Option A
  4. Quick Check:

    Minimal change but violates OCP by modifying existing class [check]
Hint: OCP: add new class, not modify existing code [check]
Common Mistakes:
4. Consider a non-thread-safe iterator implementation over a shared collection. Without synchronization on next(), which exact sequence of Thread 1 and Thread 2 calls can cause the iterator to return the same element twice?
medium
A. Thread 1 calls next() and completes; Thread 2 calls next() immediately after.
B. Thread 1 calls hasNext() -> true, context switch before next(); Thread 2 calls hasNext() -> true, then next(); Thread 1 resumes and calls next() returning the same element.
C. Thread 1 and Thread 2 both call hasNext() and next() simultaneously, but the collection is immutable.
D. Thread 1 calls next() twice rapidly without yielding; Thread 2 never calls next().

Solution

  1. Step 1: Trace the check-then-act gap

    Thread 1 calls hasNext() and sees true, but before calling next(), context switches to Thread 2.
  2. Step 2: Thread 2 calls hasNext() and next()

    Thread 2 consumes the next element, advancing the iterator state.
  3. Step 3: Thread 1 resumes and calls next()

    Thread 1 returns the same element it saw in hasNext(), causing duplicate return.
  4. Final Answer:

    Option B -> Option B
  5. Quick Check:

    Unsynchronized check-then-act causes duplicate element return [check]
Hint: Check-then-act gap causes duplicate iteration [check]
Common Mistakes:
5. In a parking lot system, if parkVehicle() is not synchronized, which exact thread interleaving causes double-booking of the same spot?
medium
A. Thread 1 parks vehicle, Thread 2 parks vehicle simultaneously without checking availability.
B. Thread 1 updates spot status after parking, Thread 2 reads stale status and parks again.
C. Thread 1 releases spot, Thread 2 immediately parks without synchronization.
D. Thread 1 checks spot availability -> true, context switch; Thread 2 checks availability -> true; both park concurrently.

Solution

  1. Step 1: Identify the check-then-act race condition

    Without synchronization, Thread 1 reads spot as available and is preempted before marking it occupied. Thread 2 also reads available and proceeds to park.
  2. Step 2: Confirm both threads park concurrently causing double-booking

    Both threads believe the spot is free and park, leading to inconsistent state and double-booking.
  3. Final Answer:

    Option D -> Option D
  4. Quick Check:

    Unsynchronized check-then-act -> double-booking race [check]
Hint: Check-then-act without sync -> double-booking race condition [check]
Common Mistakes:
Recommended

Ready to prove it?

Pass the test and this pattern moves unknown strong while earning +1 Grip toward your certificate.

10 questions~5 mineasy hard