Track User Votes with Deduplication
Data Structure DesignAuto-graded · 19 test casesLast updated
Tests ability to maintain stateful vote tracking with idempotent operations and bounded history retrieval
Build a system that tracks voting activity across users and articles. The system must handle two operations:
vote(userId, articleId, voteType)
- Records a user's vote on an article
voteTypeis either"UP"or"DOWN"- If the user submits the same vote type on the same article multiple times in a row, only the first submission counts as an event
- If the user switches their vote on an article (UP to DOWN or DOWN to UP), the new vote counts as a separate event
getLastVotes(userId)
- Returns the user's most recent vote events, up to a maximum of 3
- Results are ordered from newest to oldest
- Each event includes
[articleId, voteType, sequenceNumber]wheresequenceNumberis a global counter that increments only when a vote event is actually recorded - Returns an empty list if the user has never voted
Your function receives batched operations and must return results for each operation in order. The vote operation returns null, while getLastVotes returns the list of recent events.
Constraints
- Multiple users and articles exist in the system
- Vote operations for the same user and article are idempotent when the vote type matches the current vote
- Sequence numbers are globally unique and increase monotonically across all recorded events
- History is limited to the 3 most recent events per user
- Users who have never voted return empty results for
getLastVotes
Examples
Example 1
Input: track_user_votes(['vote', 'vote', 'getLastVotes'], [['u1', 'a1', 'UP'], ['u1', 'a1', 'UP'], ['u1']])
Output: [None, None, [['a1', 'UP', 1]]]
Example 2
Input: track_user_votes(['vote', 'vote', 'vote', 'getLastVotes'], [['u1', 'a1', 'UP'], ['u1', 'a1', 'DOWN'], ['u1', 'a2', 'UP'], ['u1']])
Output: [None, None, None, [['a2', 'UP', 3], ['a1', 'DOWN', 2], ['a1', 'UP', 1]]]
Example 3
Input: track_user_votes(['getLastVotes', 'vote', 'getLastVotes'], [['unknown'], ['u2', 'article-7', 'DOWN'], ['u2']])
Output: [[], None, [['article-7', 'DOWN', 1]]]
Hints
Hint 1
Store the current vote state separately from the event history so you can detect duplicates per article
Hint 2
Keep a bounded list per user that never exceeds 3 entries to avoid unbounded memory growth
Hint 3
The sequence counter should only increment when a vote is actually recorded, not on duplicate submissions
Worked solution
Easy Try it yourself first — then compare your approach, complexity and edge cases.
Approach
The solution maintains two separate data structures to handle different aspects of the problem:
-
Current vote state: A nested dictionary mapping each user to their current votes per article. This lets us detect when a vote is a duplicate of an existing vote versus a new or changed vote.
-
Event history: A dictionary mapping each user to a list of their recent vote events, capped at 3 entries. This provides efficient retrieval of the last few events without storing unbounded history.
For each vote operation, we first check whether the user's current vote on that article already matches the incoming vote type. If it does, the vote is idempotent and we skip recording it. If it doesn't match (or doesn't exist), we update the current state, increment a global sequence counter, append the event to the user's history, and trim the history to its last 3 entries.
For each getLastVotes operation, we simply retrieve the user's event list and reverse it to get newest-first order.
Why this works: The per-article state map ensures we correctly identify duplicates even when a user votes on multiple articles interleaved. For example, votes UP on article A, UP on article B, then UP on article A again—the third vote is correctly identified as a duplicate because we check against the stored vote for article A specifically, not just the user's last event overall.
Time Complexity: O(n) where n is the number of operations. Each vote and getLastVotes operation takes O(1) time since hash operations, list appends, and reversing a 3-element list are all constant time.
Space Complexity: O(D + U) where D is the number of distinct (user, article) pairs that have been voted on, and U is the number of users who have voted. The current-vote map grows with D, while the history is bounded at 3 entries per user.
from typing import List
def track_user_votes(operations: List[str], arguments: List[List]) -> List:
user_current_votes = {} # userId -> {articleId: voteType}
user_event_history = {} # userId -> list of last <=3 events
global_sequence = 0
output = []
for op, args in zip(operations, arguments):
if op == "vote":
uid, aid, vtype = args
votes_by_user = user_current_votes.setdefault(uid, {})
# Check if this is a duplicate vote
if votes_by_user.get(aid) == vtype:
output.append(None)
continue
# Record new vote event
votes_by_user[aid] = vtype
global_sequence += 1
events = user_event_history.setdefault(uid, [])
events.append([aid, vtype, global_sequence])
# Keep only last 3 events
if len(events) > 3:
del events[:-3]
output.append(None)
elif op == "getLastVotes":
uid = args[0]
events = user_event_history.get(uid, [])
output.append(list(reversed(events)))
return output