Live Ranking Board for Sponsored Listings
Data Structure DesignAuto-graded · 21 test casesLast updated
Process a batch of insert, delete and top-k operations on scored items, keeping a live ranking with in-place score updates and deterministic tie-breaking.
Live Ranking Board for Sponsored Listings
You are simulating a ranking board that tracks sponsored listings. Every listing has an integer id and a numeric score. The board is driven by a batch of commands, and you must report the result of each ranking query.
You are given two parallel lists, operations and arguments, of equal length. The i-th command is operations[i] with its parameters in arguments[i]. Process them in order, starting from an empty board.
Commands
"add_ad"witharguments[i] = [ad_id, score]: put the listing on the board with the given score. If the id is already on the board, replace its score with the new one."remove_ad"witharguments[i] = [ad_id]: take the listing off the board. If the id is not on the board, do nothing."get_top_k"witharguments[i] = [k]: record the ids of theklistings with the highest scores currently on the board.
Output
Return a list containing one entry per "get_top_k" command, in the order the commands appear. Each entry is a list of ad ids ordered from highest score to lowest. Commands of the other two kinds produce no output.
Rules
- If two listings have equal scores, the one with the smaller
ad_idcomes first. - If
kis larger than the number of listings on the board, return all of them in the order described above. - If
k <= 0, or the board is empty, the entry is an empty list. - Ids may arrive as floats because the argument lists hold floats. Convert ids and
kto integers, and use the score as a float. - A query does not change the board.
Constraints
- Up to 100,000 distinct listings may be on the board.
kis usually small (at most about 100).- Both updates and queries should be efficient; a full sort on every query is too slow for large inputs.
len(operations) == len(arguments).
Examples
Example 1
Input: rank_listings(['add_ad', 'add_ad', 'add_ad', 'get_top_k', 'remove_ad', 'get_top_k'], [[101, 0.95], [102, 0.88], [103, 0.99], [2], [103], [2]])
Output: [[103, 101], [101, 102]]
Hints
Hint 1
A heap can't easily change or delete an element in the middle. Keep a dictionary from id to its current score as the source of truth, and let the heap be allowed to hold outdated entries.
Hint 2
On every add, store the score in the dictionary and push a new (-score, id) pair to the heap. When popping during a query, ignore any pair whose score doesn't equal the dictionary's current value for that id.
Hint 3
Queries must not damage the heap: collect the valid pairs while popping, skip ids you've already collected (duplicate entries can exist), and push the collected pairs back afterwards.
Worked solution
Medium Try it yourself first — then compare your approach, complexity and edge cases.
Approach
A heap gives quick access to the best element but cannot cheaply update or delete an arbitrary one. The fix is lazy deletion with two structures:
- A dictionary
scoresmapping id to its current score. This is the source of truth for which listings are live. - A min-heap of
(-score, ad_id)pairs, which behaves as a max-heap on score, with ties going to the smaller id. It may contain stale entries.
Commands:
- add_ad: write the score into the dictionary and push a new pair. Any older pair for that id is now stale because its score no longer matches the dictionary.
- remove_ad: delete the id from the dictionary (a no-op if missing). Its heap pairs become stale.
- get_top_k: pop pairs from the heap. Discard a pair if the dictionary's score for that id differs from the pair's score (removed or outdated), or if that id was already collected in this query (duplicate pair). Stop after
kvalid pairs or when the heap is empty. Then push the valid pairs back so the heap still represents every live listing, and append the ids to the output.
Why it is correct
Invariant: every live listing has at least one heap entry (-scores[id], id). add_ad creates one, and get_top_k restores everything valid that it popped, while discarding only entries that are stale or duplicates. The heap pops pairs in increasing (-score, id) order, i.e. descending score with the smaller id first on ties, so the first k valid distinct pops are exactly the top k live listings, already in the required order. Exact float comparison is safe because the pair and the dictionary value come from the same float(...) conversion. If an id is removed and re-added with the same score, the old pair looks valid again, but it is identical to the new one and the seen set ensures the id is reported once.
Edge cases: k <= 0 is clamped to 0 and gives []; k larger than the live count returns everything; removing an unknown id does nothing.
Complexity
Let H be the heap size including stale entries.
add_ad: O(log H)remove_ad: O(1)get_top_k: O((k + s) log H), wheresis the number of stale or duplicate entries discarded. Each stale entry is discarded only once, so this cost is amortized against the pushes.
Space is O(n + U), where U is the number of not-yet-cleaned stale entries.
Reference solution
import heapq
from typing import List
def rank_listings(operations: List[str], arguments: List[List[float]]) -> List[List[int]]:
scores = {}
heap = []
results = []
for op, args in zip(operations, arguments):
if op == "add_ad":
ad_id, score = int(args[0]), float(args[1])
scores[ad_id] = score
heapq.heappush(heap, (-score, ad_id))
elif op == "remove_ad":
ad_id = int(args[0])
scores.pop(ad_id, None)
elif op == "get_top_k":
k = max(0, int(args[0]))
valid = []
seen = set()
while heap and len(valid) < k:
neg_score, ad_id = heapq.heappop(heap)
score = -neg_score
if scores.get(ad_id) != score or ad_id in seen:
continue
valid.append((neg_score, ad_id))
seen.add(ad_id)
for item in valid:
heapq.heappush(heap, item)
results.append([ad_id for _, ad_id in valid])
return results