Ranked Staff Roster Across Multiple Forums with Swap-Down
Data Structure DesignAuto-graded · 21 test casesLast updated
Simulate a batch of operations on per-forum ordered staff lists, enforcing seniority rules for adding, moving down one place, and removing members.
Ranked Staff Rosters
A platform hosts many forums. Each forum keeps its own roster of staff members, ordered by seniority. The member who joined the roster earliest is the most senior (position 0), and each later joiner sits below all earlier ones. A staff member may act on another member only if they are strictly more senior (a smaller position) than that member.
You are given a list of operations and a parallel list of argument lists. Replay the operations in order on an initially empty system and return a list containing the result of every operation, in the same order.
Operations
-
add_moderator(community_id, user_id)returns a boolean. Appendsuser_idto the bottom of the roster ofcommunity_id(the least senior position). If the user is already on that roster, change nothing and returnFalse. Otherwise returnTrue. -
demote_moderator(community_id, actor_id, target_id)returns a boolean. Succeeds only if all of the following hold:- Both
actor_idandtarget_idare on the roster ofcommunity_id. actor_idis strictly more senior thantarget_id.target_idis not already in the last (least senior) position.
On success,
target_idswaps places with the member directly beneath them, and the result isTrue. Otherwise nothing changes and the result isFalse. - Both
-
remove_moderator(community_id, actor_id, target_id)returns a boolean. Succeeds only if both people are on the roster ofcommunity_idandactor_idis strictly more senior thantarget_id. On success,target_idis removed (everyone below moves up one place) and the result isTrue. Otherwise nothing changes and the result isFalse. -
get_moderators(community_id)returns a list of strings. The roster ofcommunity_idfrom most senior to least senior. If the forum is unknown or its roster is empty, return[].
Notes
- Forums are completely independent; the same user can be on several rosters with unrelated positions.
- A member cannot act on themselves, since nobody is strictly more senior than themselves.
- A removed user may be added again later, and then joins at the bottom.
- Failed operations never modify any state.
- The returned list holds
True/Falsefor the three mutating operations and a list of strings forget_moderators.
Constraints
- All ids are non-empty alphanumeric strings.
operationsandargshave the same length, at most 50,000.- Each operation name is one of the four listed above, and
args[i]contains the matching arguments in the order given. - No roster ever holds more than 1,000 members.
Examples
Example 1
Input: run_staff_roster(['add_moderator', 'add_moderator', 'add_moderator', 'get_moderators', 'demote_moderator', 'get_moderators', 'demote_moderator', 'remove_moderator', 'remove_moderator', 'get_moderators'], [['programming', 'alice'], ['programming', 'bob'], ['programming', 'charlie'], ['programming'], ['programming', 'alice', 'bob'], ['programming'], ['programming', 'alice', 'bob'], ['programming', 'bob', 'charlie'], ['programming', 'alice', 'charlie'], ['programming']])
Output: [True, True, True, ['alice', 'bob', 'charlie'], True, ['alice', 'charlie', 'bob'], False, False, True, ['alice', 'bob']]
Example 2
Input: run_staff_roster(['add_moderator', 'add_moderator', 'add_moderator', 'demote_moderator', 'get_moderators', 'remove_moderator', 'get_moderators'], [['x', 'u1'], ['x', 'u2'], ['y', 'u1'], ['x', 'u1', 'u2'], ['x'], ['x', 'u2', 'u1'], ['x']])
Output: [True, True, True, False, ['u1', 'u2'], False, ['u1', 'u2']]
Hints
Hint 1
Keep, for each forum, an ordered list of users plus a dictionary from user to current index, so membership and seniority comparisons are O(1).
Hint 2
Check every precondition before touching any data, so a failed demote or remove leaves the state exactly as it was.
Hint 3
After deleting a member from the middle of the list, every later member shifts up by one, so refresh their stored indices. Also return a copy of the list from get_moderators, not the internal one.
Worked solution
Medium Try it yourself first — then compare your approach, complexity and edge cases.
Approach
Each forum has an ordered list of users (index 0 is the most senior). Every rule in the statement reduces to comparing indices in this list. To avoid scanning for a user's index, each forum also stores a dictionary mapping user to current index.
Per operation:
- add: create the forum's structures if needed. If the user is already in the dictionary, return
False. Otherwise record indexlen(list), append, returnTrue. - demote: fail if the forum is unknown, either person is missing, the actor index is not strictly smaller than the target index, or the target is already last. Otherwise swap the target with the next element and update both dictionary entries.
- remove: same existence and seniority checks. Then delete the target from the list and dictionary, and re-index every member that was below the target (they all shifted up by one).
- get: return a copy of the list, or
[]if the forum is unknown or empty.
Why it is correct
The invariant is that for each forum, index_of[u] == i exactly when list[i] == u.
- Add appends at
len(list)and stores that index. - Demote changes only two adjacent slots and rewrites both entries.
- Remove deletes the target and rewrites the entries of exactly the shifted suffix; earlier entries are unaffected.
Given the invariant, "strictly more senior" is exactly index_of[actor] < index_of[target]. All preconditions are checked before any mutation, so failed operations leave the state unchanged. A self-action fails since the indices are equal, and an unknown forum, actor or target fails through the missing lookup.
Complexity
With k the roster size (at most 1,000):
- add: O(1) amortized
- demote: O(1)
- remove: O(k)
- get: O(k)
Over 50,000 operations the worst case is around 5×10^7 simple steps. Space is O(total memberships across all forums).
Reference solution
from typing import List
def run_staff_roster(operations: List[str], args: List[List[str]]) -> List:
rosters = {} # forum -> list of users, index 0 is most senior
index_of = {} # forum -> {user: index in that list}
out = []
def add_moderator(cid, user):
lst = rosters.get(cid)
if lst is None:
lst = []
rosters[cid] = lst
index_of[cid] = {}
pos = index_of[cid]
if user in pos:
return False
pos[user] = len(lst)
lst.append(user)
return True
def demote_moderator(cid, actor, target):
lst = rosters.get(cid)
if lst is None:
return False
pos = index_of[cid]
ia = pos.get(actor)
it = pos.get(target)
if ia is None or it is None:
return False
if ia >= it or it == len(lst) - 1:
return False
lst[it], lst[it + 1] = lst[it + 1], lst[it]
pos[lst[it]] = it
pos[lst[it + 1]] = it + 1
return True
def remove_moderator(cid, actor, target):
lst = rosters.get(cid)
if lst is None:
return False
pos = index_of[cid]
ia = pos.get(actor)
it = pos.get(target)
if ia is None or it is None:
return False
if ia >= it:
return False
del lst[it]
del pos[target]
for i in range(it, len(lst)):
pos[lst[i]] = i
return True
def get_moderators(cid):
lst = rosters.get(cid)
if not lst:
return []
return list(lst)
table = {
"add_moderator": add_moderator,
"demote_moderator": demote_moderator,
"remove_moderator": remove_moderator,
"get_moderators": get_moderators,
}
for op, a in zip(operations, args):
out.append(table[op](*a))
return out