KatInterview

Follow Graph: Following Lists and Mutual-Count Suggestions

Trees & GraphsAuto-graded · 13 test cases
MediumAuto-gradedTrees & Graphsgraphhash-mapadjacency-list

Last updated

Answer batched queries on a static directed follow graph: list direct followees and rank second-hop accounts by how many followees also follow them.

A social app stores who follows whom as a fixed, directed graph. Each pair [a, b] in follows means that user a follows user b. The graph never changes after it is given.

You receive the edge list together with a batch of queries. Answer every query in order and return all the answers.

Queries

Query i is made of operations[i] (its name) and arguments[i] (a list whose first element is the user id u being asked about).

  1. "get_following": return the users that u follows, in the order their edges appear in follows.
  2. "get_second_degree_suggestions": return accounts u might want to follow. A user c is a candidate if some user f that u follows also follows c, and c is neither u nor already followed by u.
    • The score of a candidate is the number of paths u -> f -> c, that is, how many of u's followees follow c.
    • Return the candidates sorted by score from highest to lowest. Candidates with equal scores are sorted by user id from smallest to largest.
    • Return only user ids, not scores.

Rules and edge cases

  • A user that never appears as a follower (no outgoing edges), or does not appear in the graph at all, yields [] for both query types.
  • Edges are used exactly as given. If the same pair appears several times, each occurrence is a separate edge: it appears repeatedly in get_following and counts separately toward scores.
  • A self-loop [x, x] is a normal edge, so it appears in get_following(x). A user is never suggested to themselves.
  • A name other than the two above is invalid input and should raise ValueError.

Output

Return a list with one entry per query, in the same order. Each entry is a list of integers.

Constraints

  • Up to 10^5 users and up to 10^6 edges.
  • len(operations) == len(arguments), and each arguments[i] holds the single user id u.
  • Each suggestion query should take about 2 seconds at most, so build the adjacency structure once and do not rescan the whole edge list per query.

Examples

Example 1

Input: follow_graph_queries([[1, 2], [1, 3], [2, 4], [3, 4], [3, 5]], ['get_following', 'get_second_degree_suggestions'], [[1], [1]])

Output: [[2, 3], [4, 5]]

Hints

Hint 1

Build an adjacency list from follower to followees once, before processing any query.

Hint 2

For a suggestion query, put u's direct followees in a set so you can exclude them in O(1), then walk each followee's own followees and increment a counter.

Hint 3

Skip a candidate if it equals u or is in the direct set. Sort the counter's keys by the pair (-score, user_id) to get the required ordering.