KatInterview

Live Ranking Board for Sponsored Listings

Data Structure DesignAuto-graded · 21 test cases
MediumAuto-gradedData Structure Designheaphash-maplazy-deletion

Last 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" with arguments[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" with arguments[i] = [ad_id]: take the listing off the board. If the id is not on the board, do nothing.
  • "get_top_k" with arguments[i] = [k]: record the ids of the k listings 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_id comes first.
  • If k is 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 k to 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.
  • k is 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.