← Questions

Shortest relationship path between two people

0
GoogleCodingLast asked Feb 2026

A coding interview question asked in Google's first round (coding), last asked Feb 2026. It tests graphs and bfs.

People are connected by direct relationships (friend, colleague, family; each is an undirected link). Given two people, return the shortest chain of people that connects them, from the first to the second, or an empty list if no chain exists.

Interface

Unless you agree on a different interface with the interviewer, assume:

  • shortest_chain(relations: list[tuple[str, str]], a: str, b: str) -> list[str] — the people on a shortest path from a to b, both included; [a] when a == b; [] when they are not connected.

Example

relations = [("ana", "ben"), ("ana", "cara"), ("ben", "dev"), ("cara", "dev"), ("dev", "eli")]

shortest_chain(relations, "ana", "eli")   ->  ["ana", "ben", "dev", "eli"]   # or via "cara"
shortest_chain(relations, "ana", "fay")   ->  []
shortest_chain(relations, "dev", "dev")   ->  ["dev"]

Constraints

  • Up to 10^5 people and 10^6 relationships.
  • Relationships are undirected and unweighted.

Clarifying questions

  • Are relationships symmetric?
  • If several shortest chains exist, is any one acceptable?
  • What if a person in the query does not appear in any relationship?
  • One query, or many queries on the same graph?

What a strong answer covers

  • Building an adjacency list from the relationship pairs.
  • Breadth-first search from a, recording each person's parent when first reached, stopping at b; rebuilding the path by walking parents back.
  • Why BFS gives the shortest chain in an unweighted graph, and why DFS does not.
  • O(V + E) time and space; edge cases for unknown people and a == b.

Follow-ups

  • The graph is huge: search from both ends at once (bidirectional BFS) and explain the saving.
  • Relationships have strengths or costs: switch to Dijkstra.
  • Return every shortest chain, or the number of them.

Where it's asked

  • Google · First round: coding · Last asked Feb 202645 min · Coding in a Google Doc, no syntax highlighting or autocomplete · No AI

What it tests

graphs · bfs

Write and test your solution herePython in your browser, the question's tests level by level, every submission kept for you.Sign in to start coding