Gather Unique Items Across a Linked Collection Graph
Trees & GraphsAuto-graded · 16 test casesLast updated
Run a breadth-first traversal over a directed graph of folders, emitting each item once in first-seen order, while validating every reference and handling cycles.
Gather Unique Items Across a Linked Collection Graph
A catalog is organized into collections. Each collection holds a list of items and may point to other collections. These pointers form a directed graph, which may contain cycles, self-references, and collections reachable by several routes.
You are given collections, a dictionary mapping a collection ID to a record, and a root_id. Each record is a dictionary with two keys:
"pins": a list of item IDs (strings) stored in that collection."children": a list of collection IDs (strings) that the collection points to.
Return the list of item IDs in the order in which they are first encountered during a breadth-first traversal that starts at root_id.
Traversal rules
- Use a standard FIFO queue that initially contains only
root_id. - When a collection is taken from the queue, first go through its
"pins"in list order, then go through its"children"in list order and enqueue them. - Each collection is processed at most once. Mark a collection as visited at the moment it is enqueued (the root is marked before the loop starts), so cycles and shared children never cause duplicate processing.
- An item ID is appended to the output only the first time it is seen. Later occurrences, whether in the same collection or in another one, are ignored.
Validation
Before traversing, check the input. Raise a ValueError if any of the following holds:
root_idis not a key ofcollections.- Any collection ID listed in the
"children"of any record (even one not reachable from the root) is not a key ofcollections.
No partial result should be returned when an error is raised.
Constraints
1 <= len(collections) <= 20,000- Total number of items across all collections is at most
100,000. - Total number of child links across all collections is at most
100,000. - All collection IDs and item IDs are non-empty strings.
- Every record contains both
"pins"and"children"as lists.
Examples
Example 1
Input: gather_unique_items({'board_1': {'pins': ['pin_a', 'pin_b'], 'children': ['board_2', 'board_3']}, 'board_2': {'pins': ['pin_b', 'pin_c'], 'children': ['board_4']}, 'board_3': {'pins': ['pin_c', 'pin_d'], 'children': []}, 'board_4': {'pins': ['pin_e'], 'children': ['board_1']}}, 'board_1')
Output: ['pin_a', 'pin_b', 'pin_c', 'pin_d', 'pin_e']
Hints
Hint 1
Two different things need to be deduplicated: collections (to stop cycles and repeated work) and items (to emit each only once). Use a separate set for each.
Hint 2
Mark a collection as visited when you push it onto the queue, not when you pop it, and mark the root before the loop begins.
Hint 3
Because the error rule covers every record, run a full validation pass over all child references before starting the BFS rather than checking lazily during traversal.
Worked solution
Medium Try it yourself first — then compare your approach, complexity and edge cases.
Approach
This is a breadth-first search with two independent deduplication needs.
- Collections: a
visitedset prevents infinite loops on cycles and self-references, and prevents a shared child from being processed more than once. - Items: a
seen_itemsset together with an output list ensures each item is emitted only the first time it appears. A collection being new says nothing about whether its items are new, so the two sets cannot be merged.
The output order is completely determined by the rules: FIFO queue, items of a collection in list order when it is dequeued, then children enqueued in list order. There are no ties to break.
Validation first
The error rule applies to every record, including ones that cannot be reached from the root. A lazy check during BFS would miss dangling references in unreachable parts of the graph. So a full pass runs before the traversal, checking that the root exists and that each child ID is a key of collections. This also guarantees no partial output is produced on failure and that the BFS never hits a missing key.
Mark on enqueue
Marking a collection visited when it is pushed (and the root before the loop) means each collection enters the queue at most once. This keeps the queue at O(number of collections) and ensures that a back-edge to the root is ignored.
Why it is correct
- Termination: each collection is enqueued at most once and there are finitely many.
- Completeness: every collection reachable from the root is eventually enqueued, since a collection is skipped only if it is already in or has passed through the queue.
- Order: the dequeue order is BFS order with children in list order, and within a collection items are scanned in list order. Appending an item exactly when it is first seen yields the sequence of first occurrences in that order.
Complexity
Let C be the number of collections, P the total items, and E the total child links.
- Time: O(C + P + E), since validation and traversal each touch every record, item, and link a constant number of times (average-case O(1) set operations).
- Space: O(C + P) for the sets, queue, and output.
Reference solution
from collections import deque
from typing import Dict, List
def gather_unique_items(collections: Dict[str, Dict[str, List[str]]], root_id: str) -> List[str]:
if not isinstance(collections, dict):
raise ValueError("collections must be a dictionary")
if not isinstance(root_id, str) or not root_id or root_id not in collections:
raise ValueError("root_id must identify an existing collection")
for cid, record in collections.items():
if not isinstance(cid, str) or not cid:
raise ValueError("collection IDs must be non-empty strings")
if not isinstance(record, dict):
raise ValueError("each collection must be a dictionary")
pins = record.get("pins")
children = record.get("children")
if not isinstance(pins, list) or not isinstance(children, list):
raise ValueError("each collection must contain pins and children lists")
for pin in pins:
if not isinstance(pin, str) or not pin:
raise ValueError("item IDs must be non-empty strings")
for child in children:
if not isinstance(child, str) or not child or child not in collections:
raise ValueError("every child must identify an existing collection")
result = []
seen_items = set()
visited = {root_id}
queue = deque([root_id])
while queue:
cid = queue.popleft()
record = collections[cid]
for pin in record["pins"]:
if pin not in seen_items:
seen_items.add(pin)
result.append(pin)
for child in record["children"]:
if child not in visited:
visited.add(child)
queue.append(child)
return result