KatInterview

Minimum Collections to Link Two Items

Trees & GraphsAuto-graded · 24 test cases
MediumAuto-gradedTrees & Graphsgraph-theorybfsbipartite-graph

Last 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, where collections[i] contains the item IDs present in collection i
  • source_item: The starting item ID (integer)
  • target_item: The destination item ID (integer)

Output:

  • Return 0 if source_item equals target_item
  • Return the minimum number of collections needed to connect the two items if a path exists
  • Return -1 if no connection path exists

Constraints:

  • 0 <= len(collections) <= 1000
  • 0 <= len(collections[i]) <= 500
  • Item IDs are non-negative integers
  • source_item and target_item are 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