Problem
You are given a set of pairwise relationships between entities (people/services/etc.). Treat each relationship as an undirected edge in a graph.
Given:
-
relationships
: a list of pairs
[u, v]
, meaning
u
is related to
v
.
-
start
: the starting entity.
-
target
: the destination entity.
Task
-
Build an adjacency structure (e.g., a hash map from node → neighbors).
-
Use
BFS
to find the
minimum number of relationship-hops
from
start
to
target
.
Output
Return the length of the shortest path in hops (number of edges). If target is unreachable, return -1.
Follow-ups (discuss, no need to fully implement unless asked)
-
Return the actual path (list of nodes) instead of only its length.
-
Handle many queries (
start
,
target
) efficiently.
-
Consider directed relationships (only
u → v
).
Constraints (reasonable assumptions)
-
1 ≤ len(relationships) ≤ 2e5
-
Node IDs are strings or integers.
-
Graph may be disconnected.