Replayable Library Lending Operations
Data Structure DesignAuto-graded · 17 test casesLast updated
Simulate a book catalog with case-insensitive title/author search and atomic borrow/return state transitions replayed from an operation log.
You are building the core of a small lending library. Every book has a string id, a title, an author, and an availability flag that starts out as available for every book in the catalog.
You must implement a function that replays a recorded log of user actions against the catalog and reports what each action returned.
The function receives:
books: a list of dicts, each with keys"id","title", and"author". All ids are distinct.operations: a list of operation names, each one of"search_books","borrow_book", or"return_book".arguments: a list of argument lists, parallel tooperations.
For each operation, apply it to the catalog and append exactly one value to the output list, in the same order as operations:
"search_books"with arguments[query]— return a list of book snapshots, in original catalog order, for every book whosetitleorauthorcontainsqueryas a case-insensitive substring. Each snapshot is a dict with keys"id","title","author"(original casing preserved) and"is_available"reflecting the catalog's current state at the moment of the search. Ifqueryis empty, every book matches."borrow_book"with arguments[user_id, book_id]— ifbook_idexists and the book is currently available, mark it unavailable and returnTrue. If the book exists but is already checked out, returnFalse. Ifbook_iddoes not exist in the catalog, returnFalse.user_idis not stored or validated."return_book"with arguments[book_id]— ifbook_idexists, mark the book available (even if it was already available) and returnNone. Ifbook_iddoes not exist, returnNone.
Operations whose name matches none of the three above append nothing to the output list.
The books passed in must not be mutated: the catalog keeps its own internal state, and search results are independent copies.
Constraints:
- 0 ≤ number of books ≤ 10000
- 1 ≤ length of
operations= length ofarguments≤ 10000 - Book ids are unique, non-empty, and short strings.
titleandauthorare strings (possibly empty); substring matching is case-insensitive.- The same book may be searched, borrowed and returned repeatedly across the log.
Examples
Example 1
Input: replay_library_actions([{'id': '1', 'title': 'The Hobbit', 'author': 'J.R.R. Tolkien'}], ['borrow_book', 'borrow_book', 'return_book', 'borrow_book'], [['user_A', '1'], ['user_B', '1'], ['1'], ['user_B', '1']])
Output: [True, False, None, True]
Example 2
Input: replay_library_actions([{'id': '1', 'title': 'The Hobbit', 'author': 'J.R.R. Tolkien'}], ['search_books', 'borrow_book', 'search_books'], [['tolkien'], ['user_A', '1'], ['HOBBIT']])
Output: [[{'id': '1', 'title': 'The Hobbit', 'author': 'J.R.R. Tolkien', 'is_available': True}], True, [{'id': '1', 'title': 'The Hobbit', 'author': 'J.R.R. Tolkien', 'is_available': False}]]
Hints
Hint 1
Store the catalog in a dict keyed by `id` so borrow and return are constant-time lookups; insertion order preserves catalog order for searches.
Hint 2
For search, lowercase both the query and each field and use Python's substring `in` operator — that is exactly a case-insensitive partial match.
Hint 3
Return fresh dicts from search rather than the internal records, and read `is_available` at search time so results reflect the current lending state.
Worked solution
Medium Try it yourself first — then compare your approach, complexity and edge cases.
Approach
Keep the catalog as a dictionary keyed by book id, with each value holding the id, title, author, and a mutable is_available flag initialized to True. Python dicts preserve insertion order, so iterating the catalog yields books in their original order, which is what search must report.
Then walk the operation log in parallel with the argument lists, dispatching on the operation name:
- search — lowercase the query once, then scan every record and test
needle in title.lower() or needle in author.lower(). Build a brand-new dict for each hit, copying the original title/author casing and the current availability. The empty query matches everything automatically because"" in sis alwaysTrue. - borrow — look up the record; if it is missing, return
False. Otherwise, if it is available, flip the flag toFalseand returnTrue; if it is already checked out, returnFalse. Theuser_idargument is ignored. - return — look up the record; if present, set the flag back to
True(idempotent), then returnNone. Unknown ids also produceNone.
Unrecognized operation names simply append nothing.
Why It Is Correct
- Search semantics are exactly "case-insensitive substring match on title or author": both the query and both fields are lowercased, and Python's
inperforms substring containment. - Order and isolation hold because we iterate the insertion-ordered dict and emit fresh snapshot dicts, so the returned data cannot be mutated back into internal state, and it reflects availability at the moment of the search.
- Lending state is a straightforward two-state machine per book, and each borrow/return updates it deterministically, matching the required return values (
True/False/None). - Missing ids never raise: lookups use
.get(), so both borrow and return degrade gracefully toFalse/None.
Complexity
Let N be the number of books and L the average combined title+author length.
| Operation | Time | Space |
|---|---|---|
| Setup | O(N) | O(N) |
| search | O(N·L) | O(k) for k hits |
| borrow / return | O(1) expected | O(1) |
Total across the log of length M is O(N + M·N·L) worst case, dominated by searches.
Reference Solution
from typing import List, Dict
def replay_library_actions(books: List[Dict[str, str]], operations: List[str], arguments: List[List[str]]) -> List[object]:
catalog = {}
for book in books:
catalog[book["id"]] = {
"id": book["id"],
"title": book["title"],
"author": book["author"],
"is_available": True,
}
def do_search(query: str) -> List[Dict[str, object]]:
needle = query.lower()
hits = []
for record in catalog.values():
if needle in record["title"].lower() or needle in record["author"].lower():
hits.append({
"id": record["id"],
"title": record["title"],
"author": record["author"],
"is_available": record["is_available"],
})
return hits
def do_borrow(book_id: str) -> bool:
record = catalog.get(book_id)
if record is None:
return False
if record["is_available"]:
record["is_available"] = False
return True
return False
def do_return(book_id: str) -> None:
record = catalog.get(book_id)
if record is not None:
record["is_available"] = True
return None
results = []
for operation, args in zip(operations, arguments):
if operation == "search_books":
results.append(do_search(args[0]))
elif operation == "borrow_book":
results.append(do_borrow(args[1]))
elif operation == "return_book":
results.append(do_return(args[0]))
return results