Mutual friend finder

Difficulty: HARDCategory: HLDFrequency: 1Asked On 2025-05-01

Problem Statement

Given a social graph (similar to Facebook’s friend connections), determine whether two users share a mutual friend within five degrees of separation — that is, if there exists a path of friends between them such that the total number of edges in the path is ≤ 5.

Solution

Naive Approach:

The first intuitive approach is to run a Breadth-First Search (BFS) starting from user1, exploring up to 5 levels deep, and checking whether we encounter user2.

Assuming each user has an average of k friends, the number of nodes visited grows exponentially with depth:

•Level 1: k nodes
•Level 2: k² nodes
•Level 3: k³ nodes
•Level 4: k⁴ nodes
•Level 5: k⁵ nodes

Thus, the worst-case total number of nodes visited is:

O(k + k² + k³ + k⁴ + k⁵) = O(k⁵)

For a general depth D, the time complexity becomes O(k^D).

This assumes no duplicate or cyclic connections — essentially, each friend at every level is unique. In real-world graphs, many users will overlap, and using a visited set significantly reduces unnecessary traversal.

Optimized Approach:

1.Bidirectional BFS:
2.Instead of running BFS from just user1, we simultaneously run BFS from both user1 and user2. This reduces the effective search depth from D to approximately D/2.
3.For depth D = 5, the search becomes ~2.5 levels from each side, yielding a complexity of roughly:
4.O(k^2.5 + k^2.5) = O(k^3)
5.This is a significant improvement in large or dense graphs.
6.Alternating Expansion:
7.In bidirectional BFS, rather than expanding one side entirely before switching, we alternate expansions — one level from user1, then one from user2, and so on.
8.This helps detect closer mutual friends early (e.g., at depth 1 or 2), avoiding unnecessary deeper traversal.
9.Cycle Avoidance:
10.Maintain a visited set for both BFS directions to prevent redundant checks and cycles.

Can We Use Multithreading?

Yes, parallelism can improve performance, especially in high-degree nodes. Some ideas:

•Parallelize per-level expansion: Each level of BFS can be expanded in parallel — distribute friends of the current frontier across threads.
•Concurrent bidirectional BFS: Run both forward and backward BFS concurrently using separate threads.
•Use thread-safe data structures for visited sets and queues (e.g., ConcurrentHashMap, ConcurrentQueue in Java).

However, keep in mind:

•Synchronization overhead might reduce gains if k is small or depth is shallow.
•Coordination between threads to detect meeting points (i.e., mutual friends) must be efficient.




Follow up:

1.How do we store the graph
2.Do we process each of the queries on a single node or multipl nodes
3.How do query the adjacent nodes?
4.Write interfaces
Comments