Photo Slideshow with Ranked Comment Threads and Safe Voting
Data Structure DesignModel answerLast updated
Design a slideshow widget plus per-photo comment threads with idempotent voting and fast top-k ranking, scaling to 10^5 photos and 10^6 comments.
You are building a photo slideshow widget with a discussion area under each photo. Design and implement the underlying data structures and APIs.
Slideshow behavior
- Move to the next or previous photo, wrapping around at both ends.
- Autoplay, advancing at a configurable interval.
Discussion per photo
- Create, read, edit and delete comments.
- Users can upvote or downvote a comment.
- Return the top-k comments for a photo, ordered by score (highest first). Ties are broken by recency (newer first).
Scale
Up to 10^5 photos and 10^6 comments in total. A single photo may be very popular and hold a large share of them.
What to deliver
- The data structures you would use, and why.
- The time and space complexity of: add comment, delete comment, change vote, top-k query.
- The HTTP-style API you would expose, including how comments are paginated.
- How you prevent double-counting when a user rapidly toggles their vote (for example up, down, up in quick succession, or a retried request).
- Edge cases: empty slideshow, single photo, deleting a comment,
klarger than the thread, voting on a missing comment, and large time jumps for autoplay.
You may write code or pseudocode, but the focus is on the design, the invariants and the trade-offs.
Hints
Hint 1
Keep the slideshow and the comment system as independent components. The slideshow is just a cyclic index; think about how to make autoplay testable without threads or sleeping.
Hint 2
Rank comments with an ordered index per photo keyed by (-score, -sequence, id), and a hash map from comment id to the comment. A vote changes the key, so think about what you must remove and re-insert.
Hint 3
Do not store 'upvote' events. Store each user's current vote per comment (-1, 0, +1) and apply only the difference between new and old state; this makes retries and rapid toggles harmless.
Model answer
Medium Try it yourself first — then compare your approach, complexity and edge cases.
Approach
Split the problem into three parts that share only photo IDs: the slideshow, the comment store, and the voting layer.
1. Slideshow: cyclic index plus a logical clock
Keep photos as a list and cur as an index. Navigation is cur = (cur ± 1) % n, which is O(1).
For autoplay, avoid threads and sleep in the core logic. Expose tick(now) that computes steps = (now - last) // interval, advances by steps modulo n, and sets last += steps * interval. The UI drives tick from a timer. Benefits:
- Deterministic and unit-testable.
- A large time jump (tab in the background) advances several steps correctly with modulo arithmetic.
- Manual navigation or changing the interval resets
last, so the user is not skipped past immediately after clicking.
Edge cases: with no photos, navigation returns None; with one photo, next and prev stay put; a non-positive interval disables autoplay.
2. Comments: hash map plus one ordered index per photo
comments: dict[id -> Comment]gives O(1) lookup for edit, delete and vote.ranked[photo_id]: a balanced-tree or skip-list structure (in Python,SortedList; in production, a Redis sorted set) keyed by(-score, -seq, id). Its natural order is highest score first, then newest.seqis a global monotonic counter, which is safer than wall-clock time because timestamps can collide.timeline[photo_id]: an append-only list of ids in creation order for the chronological view. Deleted entries are tombstoned and skipped, so cursor positions remain stable.
3. Voting: store state, not events
Keep votes[(comment_id, user_id)] in {-1, 0, +1}. The API is set_vote(user, comment, value), never increment().
def set_vote(user, cid, value, client_seq):
c = comments.get(cid)
if c is None or c.deleted:
raise NotFound
if client_seq <= last_seq.get((cid, user), 0):
return c.score # stale or duplicate request
last_seq[(cid, user)] = client_seq
old = votes.get((cid, user), 0)
if old == value:
return c.score # no-op
ranked[c.photo].remove(c.key()) # key depends on score
c.score += value - old
votes[(cid, user)] = value
ranked[c.photo].add(c.key())
return c.score
Why this prevents double-counting:
- The score moves by
new - old, so replaying the same request changes nothing. - Up, down, up collapses to the final state; one call moves the score by at most 2.
- Out-of-order delivery is handled by a per-(user, comment) monotonically increasing
client_seq; anything at or below the stored value is dropped. - In production, add an idempotency key, client-side debouncing, and a per-comment lock or an atomic compare-and-swap so two concurrent requests from one user cannot both read the same
old. In a database, a unique key on(comment_id, user_id)plus anUPDATE ... SET score = score + :deltain one transaction does the same job.
Invariants
- Score:
score(c) = sum of votes[(c, u)]over all users. Each call applies exactlynew - old. - Order: a comment's key changes only when its score changes, and we always remove the old key before inserting the new one, so the first
kentries ofrankedare exactly the top-k.
Complexity
Let m be the comments on one photo, C total comments, V total votes, P photos.
| Operation | Time |
|---|---|
| next / prev / tick | O(1) |
| add comment | O(log m) |
| edit comment | O(1) |
| delete comment | O(log m) |
| change vote | O(log m) |
| top-k | O(log m + k) |
| paginate by time | O(log m + limit) |
Space is O(P + C + V). Even a very hot photo costs only logarithmic work per operation.
Alternatives. A heap with lazy deletion makes updates cheap but top-k costs O(k log m) and rank-based pagination is awkward. A balanced BST or skip list is equivalent to the sorted list.
API
GET /photos/{id}/comments?sort=new&cursor=&limit=20 -> {items, next_cursor}
GET /photos/{id}/comments?sort=top&cursor=&limit=20 -> {items, next_cursor}
POST /photos/{id}/comments {text} -> comment
PATCH /comments/{cid} {text} (author only)
DELETE /comments/{cid} (author only)
PUT /comments/{cid}/vote {value, client_seq}
Use PUT for votes because the operation is idempotent by construction.
Pagination
- Newest-first uses a keyset cursor (the last
seqseen). It is stable when new comments arrive, unlike offset pagination. - Top view: the cursor is the last seen key
(-score, -seq, id). Because scores change between page loads, a comment can move across pages, so a user may see a duplicate or miss one. State this trade-off; if strict consistency matters, snapshot the ranking for the session.
Edge cases
- Empty slideshow returns
None; one photo wraps onto itself. klarger than the thread returns everything.- Voting on a deleted or missing comment fails with 404; editing or deleting someone else's comment fails with 403.
- A vote of
0clears the user's vote; the same value twice is a no-op. - Deleting a comment removes it from the map and the ranked index, and tombstones it in the timeline. Its votes can be dropped lazily.
- Deleting a photo cascades to its comments, or orphans them deliberately.
Common mistakes
- Using
upvote()/downvote()as increments, which double-counts on retries. - Forgetting to remove the old key before changing the score, leaving a stale entry in the ordered index.
- Breaking ties with wall-clock time that can collide.
- Using offset pagination for a feed that changes under the reader.
- Running autoplay on a real thread inside the core logic, which makes it untestable.
- Rebuilding or sorting the whole thread on every top-k query, which is O(m log m) per request.