Minimum Collections to Link Two Items
Trees & GraphsAuto-graded · 24 test casesLast updated
Tests bipartite graph traversal and BFS to find shortest paths alternating between items and their containing collections.
You are given a list of collections, where each collection contains multiple items identified by integers. Your task is to determine the minimum number of collections needed to form a connection path between two specific items.
Two items are linked through a collection if both appear in that collection. A connection path between two items is formed by a sequence of collections where consecutive collections share at least one item in common.
Write a function that calculates the shortest such path length, measured by the number of collections traversed.
Input:
collections: A list of lists, wherecollections[i]contains the item IDs present in collectionisource_item: The starting item ID (integer)target_item: The destination item ID (integer)
Output:
- Return
0ifsource_itemequalstarget_item - Return the minimum number of collections needed to connect the two items if a path exists
- Return
-1if no connection path exists
Constraints:
0 <= len(collections) <= 10000 <= len(collections[i]) <= 500- Item IDs are non-negative integers
source_itemandtarget_itemare non-negative integers- The same item may appear multiple times within a single collection
- Collections may be empty
Examples
Example 1
Input: min_collections_connecting([[1, 2], [2, 3]], 1, 3)
Output: 2
Example 2
Input: min_collections_connecting([[1, 2, 3], [4, 5]], 1, 3)
Output: 1
Example 3
Input: min_collections_connecting([[10, 20], [20, 30], [30, 40]], 10, 40)
Output: 3
Example 4
Input: min_collections_connecting([[1, 2], [2, 3]], 2, 2)
Output: 0
Hints
Hint 1
Think of this as a bipartite graph with items on one side and collections on the other
Hint 2
Use BFS starting from the source item, alternating between items and collections
Hint 3
Mark each collection as visited once you've processed it to avoid redundant work
Worked solution
Medium Try it yourself first — then compare your approach, complexity and edge cases.
Approach
This problem requires finding the shortest path in a bipartite graph structure. One partition contains items, and the other contains collections. An edge exists between an item and a collection whenever that item belongs to that collection.
The key insight is that any path connecting two items must alternate: item → collection → item → collection → item. The path length we want counts how many collections appear in this alternating sequence.
We solve this using breadth-first search (BFS) starting from the source item:
-
Preprocess: Build a reverse index mapping each item to all collections containing it. This allows efficient traversal from items to collections.
-
BFS traversal: Start with the source item at distance 0. For each item we visit:
- Look up all collections containing it
- For each unvisited collection, mark it visited and explore all items it contains
- Each item reached through a new collection is at distance
current_distance + 1
-
Critical optimization: Mark each collection as visited the first time we expand it. Since BFS explores in increasing distance order, the first time we reach a collection is optimal. Re-expanding it would only produce equal or worse distances for its items.
-
Early termination: As soon as we encounter the target item, return immediately. BFS guarantees this is the minimum distance.
-
Edge cases: Return 0 if source equals target. Return -1 if either item appears in no collections or if the BFS exhausts without finding the target.
Why It Works
BFS guarantees that items are processed in non-decreasing order of distance. When we first reach a collection from an item at distance d, any future arrival at that same collection must come from distance ≥ d, providing no benefit. Therefore, visiting each collection exactly once is both correct and optimal.
Complexity
Time: O(C + M), where C is the number of collections and M is the total number of item-collection memberships across all collections. We visit each collection at most once and process each membership exactly once during preprocessing and BFS.
Space: O(M) for the reverse index, plus O(I + C) for the queue, visited set, and distances map, where I is the number of distinct items.
Solution
from collections import defaultdict, deque
from typing import List
def min_collections_connecting(collections: List[List[int]], source_item: int, target_item: int) -> int:
if source_item == target_item:
return 0
item_to_collections = defaultdict(list)
for collection_idx, items in enumerate(collections):
for item in set(items):
item_to_collections[item].append(collection_idx)
if source_item not in item_to_collections or target_item not in item_to_collections:
return -1
item_distances = {source_item: 0}
visited_collections = set()
queue = deque([source_item])
while queue:
current_item = queue.popleft()
current_distance = item_distances[current_item]
for collection_idx in item_to_collections[current_item]:
if collection_idx in visited_collections:
continue
visited_collections.add(collection_idx)
new_distance = current_distance + 1
for next_item in set(collections[collection_idx]):
if next_item == target_item:
return new_distance
if next_item not in item_distances:
item_distances[next_item] = new_distance
queue.append(next_item)
return -1