Shelf Command Simulator with Versioned Edits and Durable Bookmarks
Data Structure DesignAuto-graded · 16 test casesLast updated
Simulate a shelf of books with positional ordering, version-checked edits and ID-based bookmarks that survive reordering and are cleaned up on deletion.
Shelf Command Simulator
You are building the engine behind a small in-memory library shelf. The shelf holds books in a user-controlled order, and readers can leave bookmarks inside books. A book's identity (its book_id) never changes, but its place on the shelf can. Bookmarks must therefore follow the book's identity, not its slot.
Write a function that receives a list of command names and a parallel list of argument lists. It runs the commands in order against one fresh, initially empty shelf and returns the result of each command, in order.
Commands
params[i] holds the positional arguments of commands[i].
| Command | Arguments | Behavior | Result |
|---|---|---|---|
add_book | book_id, title, content or book_id, title, content, position | Creates a book with version 1. If position is omitted or None, the book goes at the end of the shelf. Otherwise it is inserted so that it ends up at index position. | True on success. False if book_id already exists or position is outside [0, N], where N is the current number of books. Failure changes nothing. |
get_book | book_id | Looks up a book. | A dict {"id", "title", "content", "version"}, or None if the book does not exist. |
update_book | book_id, new_title, new_content, expected_version | Version-checked edit. If the book exists and its current version equals expected_version, replace the title with new_title if it is not None, replace the content with new_content if it is not None, then increase the version by 1. | True on success. False if the book is missing or the version differs. |
remove_book | book_id | Removes the book from the shelf and deletes every bookmark that points to it. | True if removed, False if the book does not exist. |
move_book | book_id, new_position | Takes the book off the shelf and puts it back so that its final index is new_position. The other books keep their relative order. | True on success. False if the book is missing or new_position is outside [0, N-1]. |
get_order | none | Reads the current shelf layout. | A list of book_id values from index 0 onward. |
set_bookmark | bookmark_id, book_id, char_offset | Creates a bookmark, or overwrites the one with the same bookmark_id. | True on success. False if the book does not exist or char_offset is not in [0, len(content)]. Failure leaves any existing bookmark with that ID unchanged. |
get_bookmark | bookmark_id | Reads a bookmark. | {"bookmark_id", "book_id", "char_offset"}, or None if it does not exist or was deleted along with its book. |
Rules to get exactly right
- Bookmarks refer to a
book_id, never to a shelf index, so reordering books never changes what a bookmark points to. - Removing a book deletes all of its bookmarks. If the same
book_idis added again later, it is a brand-new book with version1, and the old bookmarks do not come back. - An
update_bookcall with a matching version and bothnew_titleandnew_contentequal toNonestill succeeds and still increases the version. - Updating content does not revalidate or change existing bookmarks, even if an offset is now beyond the new content length.
- Overwriting a bookmark with a different
book_idre-points it to the new book. Removing the old book afterwards must not delete it. - A bookmark offset equal to
len(content)is valid. - The dicts and lists you return must be copies, so later commands cannot alter earlier results.
Output
Return a list with exactly one entry per command, in the same order as commands.
Constraints
len(commands) == len(params), and every command name is one of the eight listed above.- Titles and contents are non-empty strings.
book_idandbookmark_idare alphanumeric strings.- Positions, offsets and versions are integers.
- Inputs are small enough that an O(N) shelf operation per command is fine.
Examples
Example 1
Input: run_shelf_commands(['add_book', 'add_book', 'get_order', 'set_bookmark', 'move_book', 'get_bookmark', 'update_book', 'update_book', 'remove_book', 'get_bookmark'], [['b1', 'Title 1', 'Hello World'], ['b2', 'Title 2', 'Sample Content'], [], ['mark1', 'b1', 6], ['b2', 0], ['mark1'], ['b1', None, 'Hello Universe', 1], ['b1', None, 'Conflict', 1], ['b1'], ['mark1']])
Output: [True, True, ['b1', 'b2'], True, True, {'bookmark_id': 'mark1', 'book_id': 'b1', 'char_offset': 6}, True, False, True, None]
Hints
Hint 1
Keep three separate pieces of state: a map from book_id to its record, a list holding only book_ids for the layout, and a map from bookmark_id to a record that stores a book_id (never an index).
Hint 2
Validate positions yourself: Python's list.insert silently clamps out-of-range indexes. add_book allows [0, N], while move_book allows [0, N-1] and means the final index after removing then reinserting.
Hint 3
On remove_book, delete the book, take it out of the order list, and drop every bookmark whose book_id matches. Check the rules for failed set_bookmark calls and for update_book with both fields None.
Worked solution
Medium Try it yourself first — then compare your approach, complexity and edge cases.
Approach
The core idea is to keep identity and layout apart. A book's book_id is permanent, while its shelf index changes whenever books are added, moved or removed. If bookmarks stored indexes, every reorder would silently corrupt them. So the shelf keeps three independent structures:
books: a dict frombook_idto the record (id,title,content,version), giving O(1) lookup.order: a list containing onlybook_idvalues, which is the shelf layout.bookmarks: a dict frombookmark_idto a record that stores abook_idand an offset, never a position.
The driver function builds one shelf, maps each command name to the matching method, and calls the method with the unpacked arguments. It collects the results in order.
Operation details
- add_book: reject duplicate IDs. Treat
Noneas "append". Validate the position explicitly in[0, N], becauselist.insertwould clamp bad values. New books start at version 1. - update_book: succeeds only if the book exists and
expected_versionequals the stored version (optimistic concurrency). It applies whichever of title or content is notNone, then always increments the version, even if both areNone. Bookmarks are not touched. - remove_book: deletes the record, removes the ID from
order, and filters out every bookmark pointing at that book. Because those bookmarks are physically gone, re-adding the same ID later cannot bring them back. - move_book: validates
[0, N-1], removes the ID from the list, and reinserts it atnew_position. That index is the book's final index. - set_bookmark: validates that the book exists and that
0 <= char_offset <= len(content). It then writes or overwrites the record, and a failed call leaves existing state alone. Overwriting with a different book simply replaces the storedbook_id, and the old book's removal no longer matches it. - get_bookmark: returns a copy, and also returns
Noneif the referenced book is missing, as a second safeguard. - Getters return copies so callers cannot mutate internal state.
Why it is correct
Bookmarks hold only IDs, and move_book/add_book change only order, so no reorder can affect a bookmark. remove_book removes every bookmark with the matching book_id, so no dangling bookmark can exist. All bounds and failure rules are checked before any state is modified, so failed commands leave the shelf unchanged.
Complexity
Let N be the number of books and B the number of bookmarks.
add_book,move_bookand the list part ofremove_booktake O(N).remove_bookalso scans the bookmarks, so it takes O(N + B). A reverse index from book to bookmark IDs would reduce the bookmark part to the number of bookmarks on that book.get_book,update_book,set_bookmarkandget_bookmarktake O(1) apart from copying small records.get_ordertakes O(N).- Space is O(N + B + total content size).
Reference solution
from typing import List
class Shelf:
def __init__(self):
self.books = {} # book_id -> record
self.order = [] # layout: list of book_ids
self.bookmarks = {} # bookmark_id -> record
def add_book(self, book_id, title, content, position=None):
if book_id in self.books:
return False
if position is None:
position = len(self.order)
if not isinstance(position, int) or not 0 <= position <= len(self.order):
return False
self.books[book_id] = {"id": book_id, "title": title,
"content": content, "version": 1}
self.order.insert(position, book_id)
return True
def get_book(self, book_id):
book = self.books.get(book_id)
return dict(book) if book is not None else None
def update_book(self, book_id, new_title, new_content, expected_version):
book = self.books.get(book_id)
if book is None or book["version"] != expected_version:
return False
if new_title is not None:
book["title"] = new_title
if new_content is not None:
book["content"] = new_content
book["version"] += 1
return True
def remove_book(self, book_id):
if book_id not in self.books:
return False
del self.books[book_id]
self.order.remove(book_id)
self.bookmarks = {k: v for k, v in self.bookmarks.items()
if v["book_id"] != book_id}
return True
def move_book(self, book_id, new_position):
if (book_id not in self.books or not isinstance(new_position, int)
or not 0 <= new_position < len(self.order)):
return False
self.order.remove(book_id)
self.order.insert(new_position, book_id)
return True
def get_order(self):
return list(self.order)
def set_bookmark(self, bookmark_id, book_id, char_offset):
book = self.books.get(book_id)
if (book is None or not isinstance(char_offset, int)
or not 0 <= char_offset <= len(book["content"])):
return False
self.bookmarks[bookmark_id] = {"bookmark_id": bookmark_id,
"book_id": book_id,
"char_offset": char_offset}
return True
def get_bookmark(self, bookmark_id):
mark = self.bookmarks.get(bookmark_id)
if mark is not None and mark["book_id"] in self.books:
return dict(mark)
return None
def run_shelf_commands(commands: List[str], params: List[List]) -> List:
shelf = Shelf()
handlers = {
"add_book": shelf.add_book,
"get_book": shelf.get_book,
"update_book": shelf.update_book,
"remove_book": shelf.remove_book,
"move_book": shelf.move_book,
"get_order": shelf.get_order,
"set_bookmark": shelf.set_bookmark,
"get_bookmark": shelf.get_bookmark,
}
results = []
for name, args in zip(commands, params):
results.append(handlers[name](*args))
return results