Most Connected User Tracker with Variable Top-K Queries
Data Structure DesignAuto-graded · 20 test casesLast updated
Maintain distinct-contact counts for users from undirected messages, answer the top user in O(1), and return a top-k list with deterministic tie-breaking.
You are building a small tracker for a messaging service. Messages are undirected: a message between a and b counts as a contact for both users. A user's score is the number of different other users they have exchanged at least one message with.
Implement a function that simulates the tracker. It receives a list of operations and a parallel list of argument lists. For each operation, it appends one entry to the result list.
Operations
"register"with arguments[a, b]: record a message between usersaandb(both strings).- Both users become known to the tracker, even if they have no contacts yet.
- Repeated messages between the same pair count only once toward each user's score.
(a, b)and(b, a)are the same pair. - If
a == b, the user becomes known, but the message adds no contact and their score does not change. - Result entry:
None.
"most_active_user"with arguments[]: return the known user with the highest score.- Ties are broken by choosing the lexicographically smallest user name (ordinary string comparison).
- If no user is known yet, return
None.
"top_k"with arguments[k]: return a list of thekbest known users.- Order by score descending, then by name ascending for equal scores.
- If
kis larger than the number of known users, return all known users in that order. - If
k <= 0or no users are known, return an empty list.
The value of k may differ from call to call. The operations must be processed in the given order, and operations[i] uses arguments[i].
Return the list of result entries, one per operation, in order.
Constraints
operationsandargumentshave the same length.- User names are non-empty strings and are case-sensitive.
- Operation names are exactly
"register","most_active_user", or"top_k". kis an integer and may be zero, negative, or larger than the number of users.- Aim for O(1) work per
most_active_userand an efficienttop_kwhose cost does not require sorting every user whenkis small.
Examples
Example 1
Input: track_contacts(['most_active_user'], [[]])
Output: [None]
Example 2
Input: track_contacts(['register', 'register', 'most_active_user', 'top_k'], [['alice', 'bob'], ['alice', 'carol'], [], [3]])
Output: [None, None, 'alice', ['alice', 'bob', 'carol']]
Example 3
Input: track_contacts(['register', 'register', 'register', 'most_active_user', 'top_k'], [['z', 'a'], ['b', 'z'], ['a', 'b'], [], [2]])
Output: [None, None, None, 'a', ['a', 'b']]
Example 4
Input: track_contacts(['register', 'register', 'register', 'top_k', 'top_k'], [['x', 'y'], ['x', 'y'], ['x', 'x'], [10], [0]])
Output: [None, None, None, ['x', 'y'], []]
Hints
Hint 1
Keep, for each user, a set of distinct contacts. Add each side to the other's set, and only increase scores when the pair is genuinely new and the two names differ.
Hint 2
Scores only ever go up, and each register changes at most two users. So the current best user can only be replaced by one of those two users, which lets you keep the best user up to date with a couple of comparisons.
Hint 3
Compare users with the key (-score, name). For top_k, you can pick the k smallest keys with a heap-based selection, which costs O(n log k) instead of sorting everything.
Worked solution
Medium Try it yourself first — then compare your approach, complexity and edge cases.
Approach
Store, for every user, the set of distinct users they have talked to. A register(a, b) creates entries for both users if needed, and if a != b adds each to the other's set. Sets handle repeated and reversed messages automatically. A self-message only creates the user entry.
Rank users by the key (-score, name): a smaller key is better, which gives "highest score first, then smallest name".
O(1) most_active_user. Scores never decrease, and a single register changes the score of at most two users (a and b) or introduces them with score 0. Every other user's key is unchanged. If best was the minimum key before the message, the new minimum is therefore the smaller of best, a and b. So after each register we compare a and b against best and update it if either is better. The query just returns best, or None if nobody is known. Ties are handled correctly because the key includes the name.
top_k(k). Clamp k to the number of known users, return [] for k <= 0 or when no users exist, and otherwise use heapq.nsmallest(k, users, key=key). This returns the k smallest keys in sorted order, which is exactly the required ordering. It costs O(n log k), better than a full sort when k is small and never worse in order of magnitude. Because k is chosen per call, no fixed-size heap is kept between calls.
A faster alternative for repeated queries is an indexed heap or a sorted structure updated on every register (O(log n) per update), so that top_k costs about O(k log n) by popping and reinserting, or O(k) with a balanced ordered structure. The simple selection above is easier and still correct.
Complexity
Let n be the number of users and E the number of distinct contact pairs.
register: O(1) average.most_active_user: O(1).top_k(k): O(n log k) time, O(k) extra space.- Space: O(n + E). Each pair is stored twice, once in each user's set, so in the worst case, when many pairs have talked, the total can reach O(n^2). The per-user sets are what dominate memory, not the number of keys.
Reference solution
import heapq
from typing import List
def track_contacts(operations: List[str], arguments: List[List[object]]) -> List[object]:
contacts = {} # user -> set of distinct contacts
best = None # current most active user
def key(user):
return (-len(contacts[user]), user)
results = []
for op, args in zip(operations, arguments):
if op == "register":
a, b = args
if a not in contacts:
contacts[a] = set()
if b not in contacts:
contacts[b] = set()
if a != b:
contacts[a].add(b)
contacts[b].add(a)
# Only a and b can have changed (or appeared), so only they
# can displace the current best.
for user in (a, b):
if best is None or key(user) < key(best):
best = user
results.append(None)
elif op == "most_active_user":
results.append(best)
elif op == "top_k":
k = int(args[0])
if k <= 0 or not contacts:
results.append([])
else:
k = min(k, len(contacts))
results.append(heapq.nsmallest(k, contacts.keys(), key=key))
else:
raise ValueError("unknown operation")
return results