Skip to the code
cf.
+10 XP

#411 Friends of Friends

easy

A "people you may know" panel suggests users who are exactly two steps away: not a friend already, but a friend of a friend. Users are numbered 0 to n - 1, and friendships[i] = [a, b] means a and b are friends.

Write friendsOfFriends(n, friendships, user) that returns, sorted ascending, every user whose shortest distance from user is exactly 2.

Example 1

Input: n = 6, friendships = [[0,1],[0,2],[1,3],[2,3],[3,4],[2,5]], user = 0
Output: [3,5]

User 3 is a friend of 1 and 2, and user 5 is a friend of 2. User 4 is three steps away.

Example 2

Input: n = 3, friendships = [[0,1],[1,2],[0,2]], user = 0
Output: []

User 2 is a friend of user 1, but also already a direct friend of 0.

Constraints

  • 1 <= n <= 10000
  • 0 <= friendships.length <= 50000
  • 0 <= a, b, user < n, a !== b
Saved in this browser

Run tries your code on the examples. Submit runs every test, including hidden edge cases, and solves the problem when they all pass.

Ctrl + Enter runs, Ctrl + Shift + Enter submits (⌘ on a Mac).