Project

Social Network

Model a social network as a directed graph. Use BFS for degrees of separation, hash set intersection for mutual connections, and Union-Find for community detection. This is the data structure backbone of Twitter, LinkedIn, and Facebook.

BFS traversal — animated

Degrees of separation: Alice → Davestep 1/4

// Array state

Alice
src
Bob
[1]
Carol
[2]
Dave
[3]
_
[4]
→ Network: Alice(0) follows Bob(1), Carol(2). Bob follows Dave(3). Find path Alice→Dave.

// Pseudocode

1// Social Network — adjacency list graph
2class SocialNetwork:
3 graph = HashMap<userId, Set<userId>>() // adjacency list
4 
5 function addUser(id):
6 graph[id] = new Set()
7 
8 function follow(u, v):
9 graph[u].add(v) // directed: u follows v
10 // graph[v].add(u) // undirected: mutual follow
11 
12 function degreesOfSeparation(src, dst):
13 queue = [(src, 0)]
14 visited = Set([src])
15 while queue not empty:
16 (user, depth) = queue.dequeue()
17 if user == dst: return depth
18 for neighbor in graph[user]:
19 if neighbor not in visited:
20 visited.add(neighbor)
21 queue.enqueue((neighbor, depth+1))
22 return -1 // not connected

Building blocks

1 / 4
1

Graph representation — adjacency list

Use a hash map from user ID to a set of follower/following IDs. Sparse graphs (typical for social networks) are far more space-efficient with adjacency lists than an adjacency matrix.

1 of 4

Core pseudocode

social-network.pseudo
1// Social Network — adjacency list graph
2class SocialNetwork:
3 graph = HashMap<userId, Set<userId>>() // adjacency list
4 
5 function addUser(id):
6 graph[id] = new Set()
7 
8 function follow(u, v):
9 graph[u].add(v) // directed: u follows v
10 // graph[v].add(u) // undirected: mutual follow
11 
12 function degreesOfSeparation(src, dst):
13 queue = [(src, 0)]
14 visited = Set([src])
15 while queue not empty:
16 (user, depth) = queue.dequeue()
17 if user == dst: return depth
18 for neighbor in graph[user]:
19 if neighbor not in visited:
20 visited.add(neighbor)
21 queue.enqueue((neighbor, depth+1))
22 return -1 // not connected

Complexity

BFS degrees of separation — visits all reachable nodes/edgesO(V + E)

O(V + E) time

Mutual connections — hash set intersectionO(min(|A|,|B|))

O(min(|A|,|B|)) time

Community union — Union-Find with path compressionO(α(n))

O(α(n)) time

Space — adjacency list storageO(V + E)

O(V + E) time

🔍Directed vs undirected
Twitter/Instagram are directed (follow without mutual consent). Facebook/LinkedIn are undirected (connections require mutual acceptance). A directed graph stores one-way edges; undirected stores both directions or uses an undirected adjacency set.

🎯 Quick Check

Which data structure gives O(1) average-case for checking if user A follows user B?