Meta questions

Friend Recommender

MetaOnsiteMedium

A social network stores friendships as a list of pairs [a, b], meaning users a and b are friends. A pair may appear more than once and in either order, but counts only once. Implement recommend(friendships, user, k), which returns up to k user ids to suggest to user. A suggestion is never user and never someone who is already a friend of user.

Part 1: Mutual friends

Suggest only users who share at least one friend with user. Order them by the number of mutual friends, most first, breaking ties by the smaller id. Return at most k ids; return fewer if there are fewer candidates.

  1. Example 1
    k
    2
    user
    1
    friendships
    [[1,2],[1,3],[2,4],[3,4],[2,5],[6,7]]
    Output
    [4,5]

    Why: User 1's friends are 2 and 3. User 4 is a friend of both (2 mutual friends) and user 5 is a friend of 2 only (1 mutual friend). Users 6 and 7 share no friend with 1, so they are not suggested. Both candidates fit in k = 2.

Constraints

  • 0 <= len(friendships) <= 10^5
  • 1 <= friendships[i][j] <= 10^6
  • friendships[i][0] != friendships[i][1]
  • 1 <= user <= 10^6
  • 1 <= k <= 100
Import your own questions
Paste a question you were asked and get a full problem: statement, tests and a checked solution.
Import a question
Friend Recommender: Meta interview question | LoopCoach