KatInterview

Track User Votes with Deduplication

Data Structure DesignAuto-graded · 19 test cases
EasyAuto-gradedData Structure Designhash-tablestate-managementdeduplication

Last 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
  • voteType is 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] where sequenceNumber is 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