Graph Theory
Algorithms
Network Analysis
Degrees of Separation
Computational Methods

Efficient way to find degrees of separation between two nodes in a graph

Data Structures & Algorithms practice on Codemia

Step through 300+ coding interview problems with animated visualisers that show the data structure changing as the code runs. The Blind 75 are free.

Practice algorithms

Introduction

Degrees of separation between two nodes in an unweighted graph means the length of the shortest path between them measured in edges. The standard efficient solution is breadth-first search, because BFS explores the graph layer by layer and reaches each node at the minimum possible distance from the start node.

Why BFS Is the Right Default

In an unweighted graph, every edge has the same cost. That means the shortest path is simply the path with the fewest hops. BFS is designed exactly for that situation.

If node A is connected to node B, and B is connected to node C, then a BFS starting at A visits:

  • distance 0: A
  • distance 1: neighbors of A
  • distance 2: neighbors of those neighbors

The first time BFS reaches the target node, you have found the minimum degree of separation.

A Simple BFS Implementation

A practical Python implementation uses an adjacency list and a queue.

python
1from collections import deque
2
3
4def degrees_of_separation(graph, start, target):
5    if start == target:
6        return 0
7
8    visited = {start}
9    queue = deque([(start, 0)])
10
11    while queue:
12        node, distance = queue.popleft()
13
14        for neighbor in graph.get(node, []):
15            if neighbor == target:
16                return distance + 1
17            if neighbor not in visited:
18                visited.add(neighbor)
19                queue.append((neighbor, distance + 1))
20
21    return None
22
23
24graph = {
25    "Alice": ["Bob", "Carol"],
26    "Bob": ["Alice", "Dave"],
27    "Carol": ["Alice", "Eve"],
28    "Dave": ["Bob", "Eve"],
29    "Eve": ["Carol", "Dave"],
30}
31
32print(degrees_of_separation(graph, "Alice", "Eve"))

This returns 2, because one shortest route is Alice -> Carol -> Eve.

Return the Actual Path, Not Just the Distance

Sometimes the distance alone is not enough. You may also want the sequence of nodes on the shortest path.

python
1from collections import deque
2
3
4def shortest_path(graph, start, target):
5    if start == target:
6        return [start]
7
8    visited = {start}
9    queue = deque([(start, [start])])
10
11    while queue:
12        node, path = queue.popleft()
13
14        for neighbor in graph.get(node, []):
15            if neighbor == target:
16                return path + [neighbor]
17            if neighbor not in visited:
18                visited.add(neighbor)
19                queue.append((neighbor, path + [neighbor]))
20
21    return None

Then the degree of separation is simply len(path) - 1 if a path exists.

Use Bidirectional BFS for Large Graphs

If the graph is large and you only care about one pair of nodes, bidirectional BFS is often faster in practice. Instead of searching from only the start node, it searches outward from both the start and the target until the frontiers meet.

The reason it helps is that graph neighborhoods often grow quickly. Searching halfway from both ends can reduce the total number of explored nodes significantly.

A simplified version:

python
1from collections import deque
2
3
4def bidirectional_distance(graph, start, target):
5    if start == target:
6        return 0
7
8    front_a = {start}
9    front_b = {target}
10    visited_a = {start}
11    visited_b = {target}
12    distance = 0
13
14    while front_a and front_b:
15        distance += 1
16        next_front = set()
17
18        for node in front_a:
19            for neighbor in graph.get(node, []):
20                if neighbor in front_b:
21                    return distance
22                if neighbor not in visited_a:
23                    visited_a.add(neighbor)
24                    next_front.add(neighbor)
25
26        front_a = next_front
27
28        if len(front_a) > len(front_b):
29            front_a, front_b = front_b, front_a
30            visited_a, visited_b = visited_b, visited_a
31
32    return None

This version shows the idea, even though production code often keeps more explicit bookkeeping.

When BFS Is Not Enough

BFS is correct for unweighted graphs. If edges have weights, you need a shortest-path algorithm that respects those costs, such as Dijkstra’s algorithm.

So the real decision rule is:

  • unweighted graph: BFS or bidirectional BFS
  • weighted graph: Dijkstra or another weighted shortest-path method

Degrees of separation problems in social-network style graphs are usually unweighted, which is why BFS is the standard answer.

Represent the Graph Efficiently

An adjacency list is usually the right representation for sparse graphs.

python
1graph = {
2    1: [2, 3],
3    2: [1, 4],
4    3: [1],
5    4: [2],
6}

This keeps neighbor scans efficient and avoids the memory overhead of an adjacency matrix when the graph is large but not densely connected.

Common Pitfalls

The most common mistake is using DFS and hoping it will find the minimum separation just because it eventually finds a path. Another is forgetting a visited set, which can cause repeated work or infinite loops in cyclic graphs. Developers also sometimes use BFS on weighted graphs and then wonder why the answer is wrong. A final issue is storing the graph in a form that makes neighbor lookup expensive, which hurts performance even when the algorithm choice is correct.

Summary

  • In an unweighted graph, degrees of separation is a shortest-path problem in number of edges.
  • BFS is the standard efficient solution because it explores the graph in distance layers.
  • Bidirectional BFS can reduce search work for large one-pair queries.
  • Use adjacency lists for efficient graph representation in most sparse graphs.
  • If edges have weights, switch to a weighted shortest-path algorithm instead of plain BFS.

Course
Intermediate
27 lessons
15 hours
DSA Fundamentals

Master algorithmic patterns and data structures through hands-on LeetCode-style problems - from arrays and hashing to dynamic programming and advanced graphs.

View the course
Basis Lab
There is a whole course on this

Basis Lab has written “Graphs and Finding a Path”, a course that teaches this from the ground up rather than answering the single question. It is a separate product from the same team and the course is free to read.

Read the course
Data Structures & Algorithms practice on Codemia

Step through 300+ coding interview problems with animated visualisers that show the data structure changing as the code runs. The Blind 75 are free.

Practice algorithms