Article Reaction Ledger with Recent Reversal Log
Data Structure DesignAuto-graded · 18 test casesLast updated
Simulate a stream of up/down/clear reactions on articles, maintaining net scores and a bounded log of the three most recent reversals per article, all in constant time per operation.
Article Reaction Ledger
You are building a small in-memory ledger that tracks reader reactions to articles. Each reader can hold one reaction per article: "UP", "DOWN", or "NONE" (no reaction, which is also the default state for any reader/article pair that has never been voted on).
A reversal (flip) happens when a reader's reaction on an article changes directly from "UP" to "DOWN" or from "DOWN" to "UP". The following are not reversals: setting a first reaction (NONE to UP/DOWN), clearing a reaction (UP/DOWN to NONE), and repeating the reaction already held. Note that UP → NONE → DOWN contains no reversal, because the reader passes through the no-reaction state.
You are given a list of operations to process in order. Implement a function that simulates the ledger and returns one result per operation.
Operations
"vote"with arguments[user_id, article_id, new_vote]: set the reader's reaction on that article tonew_vote(one of"UP","DOWN","NONE"). If it equals the current reaction, nothing changes. The result for this operation isNone."getScore"with arguments[article_id]: the result is the number of"UP"reactions minus the number of"DOWN"reactions currently held on that article. An article that has never been seen has score0."getLast3Flips"with arguments[article_id]: the result is a list of up to the 3 most recent reversals on that article, ordered oldest to newest. Fewer than 3 are returned if fewer have occurred; an unknown article gives[].
Reversal records
Each reversal is a dictionary with exactly these keys:
"user_id": the reader who reversed their reaction"from_vote": the previous reaction ("UP"or"DOWN")"to_vote": the new reaction ("DOWN"or"UP")"sequence": an integer from a single counter shared by all articles. It starts at 0 and increases by 1 only when a reversal occurs, so the first reversal overall gets1, the next gets2, and so on. An individual article's reversals may therefore show gaps in their sequence values.
Task
Write a function that takes the list of operation names and the parallel list of argument lists, processes them in order, and returns the list of results (one entry per operation, in the same order). Each operation should be handled in O(1) time.
Constraints
operationsandargumentshave the same length.- Operation names are exactly
"vote","getScore", or"getLast3Flips". user_idandarticle_idare hashable values (for example strings or integers).new_voteis always one of"UP","DOWN","NONE".- Everything runs in a single process; no persistence is needed.
- Each operation must run in O(1) time (amortized, using hashing).
Examples
Example 1
Input: track_reactions(['vote', 'vote', 'getScore', 'getLast3Flips'], [['u1', 'a1', 'UP'], ['u1', 'a1', 'DOWN'], ['a1'], ['a1']])
Output: [None, None, -1, [{'user_id': 'u1', 'from_vote': 'UP', 'to_vote': 'DOWN', 'sequence': 1}]]
Example 2
Input: track_reactions(['vote', 'vote', 'vote', 'vote', 'getScore', 'getLast3Flips'], [[1, 'article', 'UP'], [2, 'article', 'DOWN'], [1, 'article', 'UP'], [2, 'article', 'UP'], ['article'], ['article']])
Output: [None, None, None, None, 2, [{'user_id': 2, 'from_vote': 'DOWN', 'to_vote': 'UP', 'sequence': 1}]]
Example 3
Input: track_reactions(['getScore', 'getLast3Flips'], [['missing'], ['missing']])
Output: [0, []]
Example 4
Input: track_reactions(['vote', 'vote', 'vote', 'vote', 'getLast3Flips'], [['u', 'a', 'UP'], ['u', 'a', 'NONE'], ['u', 'a', 'DOWN'], ['u', 'a', 'UP'], ['a']])
Output: [None, None, None, None, [{'user_id': 'u', 'from_vote': 'DOWN', 'to_vote': 'UP', 'sequence': 1}]]
Hints
Hint 1
Never recompute the score by scanning votes. Keep a running total per article and adjust it by the difference between the reader's old and new contribution (UP = +1, DOWN = -1, NONE = 0).
Hint 2
Look up the reader's current reaction first (default NONE). If it equals the new reaction, do nothing. Otherwise a reversal occurs only when both the old and new reactions are real votes (UP or DOWN).
Hint 3
Keep a per-article queue capped at 3 entries (for example collections.deque with maxlen=3) and one global counter that increments only when a reversal is recorded.
Worked solution
Medium Try it yourself first — then compare your approach, complexity and edge cases.
Approach
Every operation must be O(1), so nothing may be recomputed at query time. Maintain three pieces of state:
- Current reactions: a map from article to a map of reader to
"UP"or"DOWN". A missing entry means"NONE". - Running score per article, equal to the number of UP reactions minus the number of DOWN reactions.
- Bounded reversal log per article: a deque with
maxlen=3, so appending a fourth record automatically drops the oldest.
A single global integer counter provides the sequence values and is incremented only when a reversal is recorded.
For a vote:
- Look up the reader's old reaction (default
"NONE"). If it equals the new one, nothing changes. - Otherwise, undo the old contribution (UP removes +1, DOWN removes -1, NONE removes 0), then apply the new one (UP adds +1, DOWN adds -1, NONE adds 0).
- If both old and new are real reactions (they already differ), record a reversal with the next counter value.
- Store the new reaction, or delete the entry if it is
"NONE".
getScore reads the stored total (0 for unknown articles). getLast3Flips returns a copy of the deque as a list.
Why it is correct
- Score invariant: after each vote, the stored score equals UPs minus DOWNs for that article, because each vote changes exactly one reader's state and the update removes that reader's old contribution and adds the new one. This yields the deltas NONE→UP +1, NONE→DOWN -1, UP→NONE -1, DOWN→NONE +1, UP→DOWN -2, DOWN→UP +2.
- Reversal definition: a reversal needs both endpoints in {UP, DOWN} and different. Clearing, first votes, and repeated votes are excluded, and UP→NONE→DOWN is not a reversal since the intermediate state is NONE.
- Last three, oldest first: records are appended in occurrence order and the deque evicts from the left, so converting it to a list gives at most the 3 newest reversals in chronological order.
Complexity
vote,getScore,getLast3Flips: O(1) each (the final copy has at most 3 elements). Total time is O(n) for n operations.- Space: O(V + A), where V is the number of active reactions and A is the number of articles (each holding at most 3 records).
Reference solution
from collections import defaultdict, deque
from typing import List
def track_reactions(operations: List[str], arguments: List[List]) -> List:
current = defaultdict(dict) # article -> {user: "UP"/"DOWN"}
totals = defaultdict(int) # article -> up - down
recent = defaultdict(lambda: deque(maxlen=3)) # article -> last 3 reversals
counter = 0 # global reversal counter
results = []
for op, args in zip(operations, arguments):
if op == "vote":
user_id, article_id, new_vote = args
old_vote = current[article_id].get(user_id, "NONE")
if old_vote != new_vote:
if old_vote == "UP":
totals[article_id] -= 1
elif old_vote == "DOWN":
totals[article_id] += 1
if new_vote == "UP":
totals[article_id] += 1
elif new_vote == "DOWN":
totals[article_id] -= 1
if old_vote in ("UP", "DOWN") and new_vote in ("UP", "DOWN"):
counter += 1
recent[article_id].append({
"user_id": user_id,
"from_vote": old_vote,
"to_vote": new_vote,
"sequence": counter,
})
if new_vote == "NONE":
current[article_id].pop(user_id, None)
else:
current[article_id][user_id] = new_vote
results.append(None)
elif op == "getScore":
results.append(totals[args[0]])
elif op == "getLast3Flips":
results.append(list(recent[args[0]]))
return results