Shortest Supplier Chain Between Two Vendors
Trees & GraphsAuto-graded · 21 test casesLast updated
Tests BFS-based shortest-path traversal on an undirected graph, including path reconstruction and degree-of-separation counting with correct edge-case handling.
Shortest Supplier Chain Between Two Vendors
You are building a network analysis tool for a vendor directory. The directory tracks supply relationships — when one vendor regularly sources goods or services from another. Each such relationship is undirected: if vendor X supplies vendor Y, then Y also supplies X.
Given a list of supply relationships and two vendor identifiers, find the shortest chain connecting them through the supply network.
Definitions
- A chain is a sequence of vendors
[v0, v1, v2, ..., vk]where every consecutive pair(vi, vi+1)is a recorded relationship. - The link distance between two vendors is the number of edges on the shortest chain (i.e.,
len(path) - 1). - The hop count (degree) is the number of intermediate vendors on the shortest chain:
len(path) - 2. Two directly connected vendors therefore have hop count 0, and a chain of three vendors has hop count 1.
Task
Implement a function that accepts:
relationships— a list of pairs[a, b], each representing an undirected supply link between vendoraand vendorb.source— the starting vendor.target— the destination vendor.
Return a dictionary with two keys:
"path"— a list of vendor names representing the shortest chain fromsourcetotarget, inclusive. If multiple shortest chains exist, return the lexicographically smallest one (i.e., at each step along the chain, choose the neighbor that comes first alphabetically)."degree"— the hop count as defined above.
Special cases
- If
sourceandtargetare the same vendor, return{"path": [source], "degree": 0}. - If no chain exists (the two vendors are in disconnected parts of the network, or either vendor does not appear in any relationship), return
{"path": [], "degree": -1}. - A direct connection
source -> targethas hop count 0, not 1.
Constraints
0 <= len(relationships) <= 10^4- Each relationship is a list of exactly two strings:
[a, b]wherea != b. - Vendor names are non-empty strings containing only alphanumeric characters.
sourceandtargetare non-empty strings.- There may be duplicate relationships in the input; they are treated as a single link.
- Self-loops do not appear in the input.
Examples
Example 1
Input: find_vendor_supply_chain([['A', 'B'], ['B', 'C']], 'A', 'C')
Output: {'path': ['A', 'B', 'C'], 'degree': 1}
Example 2
Input: find_vendor_supply_chain([['Acme', 'Beta'], ['Beta', 'Cedar'], ['Acme', 'Delta'], ['Delta', 'Cedar']], 'Acme', 'Cedar')
Output: {'path': ['Acme', 'Beta', 'Cedar'], 'degree': 1}
Example 3
Input: find_vendor_supply_chain([['A', 'B'], ['C', 'D']], 'A', 'D')
Output: {'path': [], 'degree': -1}
Hints
Hint 1
Model the relationships as an undirected adjacency structure. Which traversal strategy is guaranteed to find the shortest path in an unweighted graph?
Hint 2
Rather than storing the full path in each queue entry, keep a parent map that records how each vendor was first reached. Once the target is found, follow parent pointers back to reconstruct the path.
Hint 3
To guarantee the lexicographically smallest path among all shortest paths, process each vendor's neighbors in sorted order before adding them to the queue.
Worked solution
Hard Try it yourself first — then compare your approach, complexity and edge cases.
Approach
Recognising the right algorithm
Every supply relationship has equal weight, so this is a shortest-path problem on an unweighted, undirected graph. Breadth-first search (BFS) is the natural fit: it explores nodes in non-decreasing order of distance from the source, so the first time it reaches the target it has found a shortest path.
Dijkstra's algorithm would also work but is unnecessary overhead here. DFS would find a path, not necessarily the shortest one.
Step-by-step plan
-
Handle the trivial case. If
source == target, return immediately with a single-node path and hop count 0. -
Build an adjacency structure. Iterate over the relationship list once, adding both directions for each pair. Using sets automatically deduplicates repeated edges.
-
Check reachability of endpoints. If either vendor never appears as a key in the adjacency map, they have no connections at all, so no path can exist.
-
BFS with a parent map. Instead of copying the growing path into every queue entry (which costs O(V · L) memory), store only a
parentdictionary that maps each vendor to the vendor it was reached from. The source maps toNone. The map doubles as the visited set: a vendor already inparentis skipped, preventing re-enqueuing and handling cycles. -
Sorted neighbor expansion. To guarantee the lexicographically smallest shortest path among all ties, process each vendor's neighbours in alphabetical order before adding them to the queue. Because BFS processes nodes level by level, the first time a vendor is reached it is reached at the minimum possible distance. Sorting within each level ensures the alphabetically earlier route is always preferred.
-
Early exit. Stop as soon as the target is dequeued. Any further BFS work is unnecessary.
-
Reconstruct the path. Follow parent pointers from
targetback tosource, collecting nodes into a list, then reverse it. -
Compute the hop count. Hop count =
len(path) - 2(intermediates only). A direct two-node path gives 0, which matches the problem's definition.
Why correctness is guaranteed
BFS processes all nodes at distance k before any node at distance k + 1. A node is assigned a parent only the first time it is seen, so its recorded distance is its true shortest distance. Following parent pointers from the target therefore traces a shortest path, with each step reducing the distance by exactly 1. The sorted expansion ensures that among equally short paths the alphabetically earliest one is always committed to the parent map first.
Edge cases
| Situation | Result |
|---|---|
source == target | {"path": [source], "degree": 0} |
| Either vendor absent from all relationships | {"path": [], "degree": -1} |
| Vendors in disconnected components | {"path": [], "degree": -1} |
Direct connection (source and target are neighbours) | hop count 0 |
| Duplicate edges in input | Deduplicated by the set-based adjacency structure |
| Multiple shortest paths | Lexicographically smallest returned via sorted neighbour expansion |
Complexity
Let V = number of distinct vendors, E = number of unique relationships.
- Time: O((V + E) log V). Building the adjacency structure is O(E). Each node is enqueued once and each edge is inspected at most twice, giving O(V + E) for BFS itself. Sorting each node's neighbours adds O(deg(v) log deg(v)) per node, which sums to O(E log V) overall. Path reconstruction is O(V).
- Space: O(V + E). The adjacency structure is O(V + E). The parent map and queue each hold at most O(V) entries.
Reference solution
from collections import deque
from typing import Dict, List
def find_vendor_supply_chain(
relationships: List[List[str]],
source: str,
target: str,
) -> Dict[str, object]:
# Same vendor: hop count 0, single-element path
if source == target:
return {"path": [source], "degree": 0}
# Build undirected adjacency list using sets to deduplicate edges
graph: Dict[str, set] = {}
for a, b in relationships:
graph.setdefault(a, set()).add(b)
graph.setdefault(b, set()).add(a)
# Either vendor is isolated (appears in no relationship)
if source not in graph or target not in graph:
return {"path": [], "degree": -1}
# BFS — parent map doubles as the visited set
queue = deque([source])
parent = {source: None}
while queue:
current = queue.popleft()
if current == target:
break
# Sort neighbors to ensure the lexicographically smallest path is chosen
for neighbor in sorted(graph.get(current, ())):
if neighbor not in parent:
parent[neighbor] = current
queue.append(neighbor)
# Target was never reached
if target not in parent:
return {"path": [], "degree": -1}
# Reconstruct path by following parent pointers from target back to source
path = []
current = target
while current is not None:
path.append(current)
current = parent[current]
path.reverse()
# max(0, ...) guards the source == target case if it ever slips through
return {"path": path, "degree": max(0, len(path) - 2)}