KatInterview

Longest Chain of Accounts Reachable Through Follows

Trees & GraphsAuto-graded · 20 test cases
MediumAuto-gradedTrees & Graphsgraphdfsrecursion

Last updated

Find the longest simple path from a start node in a directed graph with possible cycles, using backtracking DFS with a per-path visited set.

A social app stores who follows whom as a list of directed pairs. Each pair [a, b] means that user a follows user b.

Starting from a given user, you hop from a user to someone they follow, then to someone that user follows, and so on. Your goal is to find how many hops the longest possible chain can contain, under the rule that no user may appear twice in the same chain, including the starting user.

Write a function that takes the list of follow pairs and the starting user's id, and returns the number of hops in the longest valid chain beginning at that user.

Details

  • A chain starting at start_id is a sequence of distinct users start_id = u0, u1, u2, ..., uk, where each u(i) follows u(i+1).
  • Its length is k, the number of hops (equivalently, the number of users after the start).
  • Return the largest k over all valid chains.
  • Because users cannot repeat, a chain can never return to a user already in it. This is how cycles are handled: an edge leading back to a user already in the current chain is simply not usable for that chain.
  • A user may be usable in one chain and blocked in another. Different branches are judged independently, so a user blocked in one branch can still be used in a different branch.
  • If the start user follows nobody (or does not appear in the list at all), return 0.
  • A self-follow such as [1, 1] cannot be used, since it would repeat a user.
  • Duplicate pairs do not change the answer.
  • Your solution should use recursion.

Constraints

  • 0 <= len(follows) <= 20-ish in size for worst-case cyclic inputs; graphs are small enough that exploring all simple paths from the start user is feasible.
  • Each pair contains two integer user ids.
  • start_id is an integer and may or may not appear in follows.
  • Pairs may contain duplicates and self-follows.
  • The graph may contain cycles.

Examples

Example 1

Input: longest_follow_chain([[1, 2], [2, 3], [3, 4]], 1)

Output: 3

Example 2

Input: longest_follow_chain([[1, 2], [2, 1]], 1)

Output: 1

Example 3

Input: longest_follow_chain([[1, 2], [1, 3], [2, 4], [3, 5], [5, 6]], 1)

Output: 3

Hints

Hint 1

Turn the pair list into an adjacency mapping from each user to the users they follow, so you can look up neighbors quickly.

Hint 2

Do a recursive DFS that carries the set of users on the current chain. Skip any neighbor already in that set, and the base case (no usable neighbor) naturally returns 0.

Hint 3

Remove a user from the chain set after returning from its recursive call, so other branches can still use it. A single global visited set, or caching results per user alone, gives wrong answers when cycles exist.