Ordered Stage Queue: Simulate Item Promotion and Demotion
Linked ListsAuto-graded · 16 test casesLast updated
Tests whether a candidate can model item movement across ordered stages using a normalized O(1)-per-move doubly linked list structure.
Problem
You are managing a pipeline of work items organized into an ordered sequence of stages. Each item belongs to exactly one stage at any given time. Items can be promoted to the next stage or demoted to the previous one, and each such transition appends the item to the bottom of the destination stage's list.
Given the initial stage definitions, the initial placement of items, and a sequence of transition instructions, return the final ordering of items within each stage.
Input Format
initial_columns — a list of stage definition objects, each with:
"id": a unique string identifier for the stage"title": a human-readable label
Stages are ordered left to right by their position in this list.
initial_tasks — a list of item objects, each with:
"id": a unique string identifier"title": a human-readable label"columnId": the"id"of the stage this item currently belongs to
Items are given in their initial top-to-bottom display order within each stage.
moves — a list of [item_id, direction] pairs, where direction is either "left" (move to the preceding stage) or "right" (move to the following stage).
Output Format
Return a list of lists of item ID strings. The outer list has one entry per stage, in the same left-to-right order as initial_columns. Each inner list contains the IDs of items currently in that stage, ordered top to bottom.
Rules
- When an item moves, it is appended to the bottom of the destination stage.
- A transition that would move an item beyond the leftmost or rightmost stage is a no-op — the item stays where it is and its position within the stage is unchanged.
- Transitions are applied strictly in sequence; each one reads the state produced by all prior transitions.
- If an item is moved right and then left, it lands at the bottom of its original stage, not its original position.
Constraints
1 ≤ len(initial_columns) ≤ 1000 ≤ len(initial_tasks) ≤ 10^50 ≤ len(moves) ≤ 10^5- All stage
"id"values are unique strings. - All item
"id"values are unique strings. - Every item's
"columnId"refers to a valid stage"id". - Every transition's
item_idrefers to a valid item"id". directionis always"left"or"right".- Each move of a single item must run in O(1) time with respect to the total number of items.
Examples
Example 1
Input: simulate_kanban_moves([{'id': 'todo', 'title': 'To Do'}, {'id': 'in_progress', 'title': 'In Progress'}, {'id': 'done', 'title': 'Done'}], [{'id': '1', 'title': 'Setup Repo', 'columnId': 'todo'}, {'id': '2', 'title': 'Write Tests', 'columnId': 'todo'}, {'id': '3', 'title': 'Deploy', 'columnId': 'in_progress'}], [['1', 'right']])
Output: [['2'], ['3', '1'], []]
Hints
Hint 1
Track which stage each item currently lives in using a dictionary so you never need to scan all items to locate one.
Hint 2
Removing an item from the middle of a list is expensive unless each item knows its immediate neighbors — think about what data structure gives you O(1) unlinking.
Hint 3
Appending to the bottom of a stage only requires updating that stage's tail pointer; keep a head and tail pointer per stage to make both removal and insertion O(1).
Worked solution
Medium Try it yourself first — then compare your approach, complexity and edge cases.
Approach
The straightforward model — one Python list per stage — fails the O(1)-per-move requirement. Removing an item from the middle of a Python list takes O(k) where k is the number of items in that stage, because everything after the gap shifts left. With up to 10^5 items and 10^5 moves, that degrades to O(N·M) in the worst case.
The fix is to represent each stage's ordered contents as a doubly linked list backed by two hash maps (prev_node and next_node) rather than a Python list. Every item knows its immediate predecessor and successor, so splicing it out only requires updating two pointers — O(1) regardless of stage size. Appending to the tail of a stage is equally O(1) because we maintain an explicit tails array.
Three supporting structures complete the picture:
stage_indexmaps each stage ID to its integer position, so finding the adjacent stage (and checking boundary conditions) is O(1).item_stagemaps each item ID to its current stage index, so we never scan for an item's location.headsandtailsarrays give direct access to both ends of each stage's linked list.
Processing a move
- Look up the item's current stage index in
item_stage. - Compute the destination index (
src - 1orsrc + 1). If it falls outside[0, n_stages), skip — this mirrors a disabled navigation button. - Unlink the item: wire its predecessor's
next_nodeto its successor and vice versa, adjustingheads[src]ortails[src]if the item was at either end. - Append the item to
tails[dst], updatingheads[dst]if the destination was empty, then recorditem_stage[item_id] = dst.
Why the output is correct
Two invariants hold after every operation:
- Walking
heads[i]throughnext_nodevisits exactly the items whoseitem_stageequalsi, in display order. prev_nodeandnext_nodeare mutually consistent at all times.
Both hold after initialization (items are appended in input order). Each move preserves them: the splice removes exactly one node cleanly, and the append attaches it at exactly one new position.
Out-of-bounds moves are skipped before any mutation, so they cannot corrupt state. Because moves are applied sequentially and each one reads the state the previous one left, "move right then move left" correctly lands the item at the bottom of its original stage rather than its original position — that is the specified behavior.
Complexity
| Phase | Time | Space |
|---|---|---|
| Build stage index and linked lists | O(C + T) | O(C + T) |
| Each individual move | O(1) | O(1) extra |
| All M moves | O(M) | — |
| Collect output | O(C + T) | O(T) output |
Overall: O(C + T + M) time and O(C + T) space, where C is the number of stages, T the number of items, and M the number of moves. A single move does not depend on T.
Edge cases
- Empty stage:
heads[i]andtails[i]are bothNone. Appending the first item sets both. Removing the last item resets both toNone. The output for that stage is[]. - Single-stage pipeline: Every move targets index
-1or1, both out of range, so all moves are no-ops and the output equals the input order. - Item at head, middle, or tail: All three removal cases are handled by the
before is Noneandafter is Nonebranches. - Repeated moves of the same item: Each move reads the current
item_stage, so a sequence like right, right, left behaves correctly.
from typing import Dict, List, Optional
def simulate_kanban_moves(
initial_columns: List[Dict[str, str]],
initial_tasks: List[Dict[str, str]],
moves: List[List[str]],
) -> List[List[str]]:
stage_index: Dict[str, int] = {col["id"]: i for i, col in enumerate(initial_columns)}
n_stages = len(initial_columns)
heads: List[Optional[str]] = [None] * n_stages
tails: List[Optional[str]] = [None] * n_stages
prev_node: Dict[str, Optional[str]] = {}
next_node: Dict[str, Optional[str]] = {}
item_stage: Dict[str, int] = {}
for task in initial_tasks:
tid = task["id"]
idx = stage_index[task["columnId"]]
prev_node[tid] = tails[idx]
next_node[tid] = None
item_stage[tid] = idx
if tails[idx] is None:
heads[idx] = tid
else:
next_node[tails[idx]] = tid
tails[idx] = tid
for item_id, direction in moves:
src = item_stage[item_id]
dst = src - 1 if direction == "left" else src + 1
if dst < 0 or dst >= n_stages:
continue
before = prev_node[item_id]
after = next_node[item_id]
if before is None:
heads[src] = after
else:
next_node[before] = after
if after is None:
tails[src] = before
else:
prev_node[after] = before
prev_node[item_id] = tails[dst]
next_node[item_id] = None
if tails[dst] is None:
heads[dst] = item_id
else:
next_node[tails[dst]] = item_id
tails[dst] = item_id
item_stage[item_id] = dst
result: List[List[str]] = []
for idx in range(n_stages):
stage_items: List[str] = []
cur = heads[idx]
while cur is not None:
stage_items.append(cur)
cur = next_node[cur]
result.append(stage_items)
return result