Social Network Analyzer - Problem

Model a social network as a graph where each person is a node and friendships are edges. Implement functionality to:

  • Find mutual friends between two people
  • Calculate degrees of separation (shortest path between two people)
  • Suggest friends-of-friends (people connected through exactly one mutual friend)

Given a list of friendships and two people, return their mutual friends, degrees of separation, and friend suggestions for the first person.

friendships is a 2D array where each element [a, b] represents a bidirectional friendship between person a and person b.

Input & Output

Example 1 — Basic Social Network
$ Input: friendships = [[1,2],[1,3],[2,4],[3,4],[4,5]], person1 = 1, person2 = 4
Output: [[2,3],2,[5]]
💡 Note: Mutual friends of 1 and 4: [2,3] (both connected to 1 and 4). Degrees of separation: 2 (shortest path 1→2→4 or 1→3→4). Friend suggestions for person 1: [5] (friend of person 4, who is connected to 1's friends)
Example 2 — Direct Connection
$ Input: friendships = [[1,2],[2,3],[3,4]], person1 = 1, person2 = 2
Output: [[],1,[3]]
💡 Note: No mutual friends (empty array). Degrees of separation: 1 (direct friends). Friend suggestions for person 1: [3] (friend of person 2)
Example 3 — Same Person
$ Input: friendships = [[1,2],[2,3]], person1 = 1, person2 = 1
Output: [[],0,[3]]
💡 Note: Same person has 0 degrees of separation. Friend suggestions: [3] (friend of friend 2)

Constraints

  • 1 ≤ friendships.length ≤ 1000
  • friendships[i].length == 2
  • 1 ≤ person1, person2 ≤ 1000
  • All friendships are bidirectional

Visualization

Tap to expand
INPUTALGORITHMRESULT12345Friendships: [[1,2],[1,3],[2,4],[3,4],[4,5]]Find connections betweenPerson 1 and Person 41BFS2Lv134Lv2BFS Steps:1. Start at Person 12. Explore Level 1: [2,3]3. Explore Level 2: [4]4. Target Found!Mutual Friends[2, 3]Degrees of Separation2Friend Suggestions[5]Path: 1 → 2 → 4or 1 → 3 → 4Key Insight:BFS naturally finds shortest social connections by exploring level-by-level,just like how social networks spread information through degrees of separationTutorialsPoint - Social Network Analyzer | BFS Approach
Asked in
Facebook 85 LinkedIn 72 Google 45 Twitter 38
34.5K Views
High Frequency
~25 min Avg. Time
892 Likes
Ln 1, Col 1
Smart Actions
💡 Explanation
AI Ready
💡 Suggestion Tab to accept Esc to dismiss
// Output will appear here after running code
Code Editor Closed
Click the red button to reopen