Longest Chain of Accounts Reachable Through Follows
Trees & GraphsAuto-graded · 20 test casesLast 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_idis a sequence of distinct usersstart_id = u0, u1, u2, ..., uk, where eachu(i)followsu(i+1). - Its length is
k, the number of hops (equivalently, the number of users after the start). - Return the largest
kover 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_idis an integer and may or may not appear infollows.- 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.
Worked solution
Medium Try it yourself first — then compare your approach, complexity and edge cases.
Approach
Build a map from each user to the list of users they follow. Then run a recursive depth-first search from the start user, keeping a set of the users on the current chain only.
For a user u currently at the end of the chain:
- Look at every user
vthatufollows. - If
vis already on the chain, skip it, since using it would repeat a user. - Otherwise add
vto the chain, recurse to get the longest continuation fromv, and record1 + that value. - Remove
vfrom the chain (backtrack) before trying the next neighbor. - Return the best value found, or
0if no neighbor was usable.
The answer is the result of this search from start_user, with start_user already placed on the chain.
Why it is correct
- Termination: each recursive call adds a new user to the chain, and the chain can hold at most as many users as exist, so recursion always ends, even with cycles.
- Completeness: because users are removed from the chain after each branch, every simple path from the start is explored. The recursive value is the longest simple path from
uthat avoids the users already on the chain, and the maximum over all first hops gives the overall longest. - Why not a global visited set: with edges
1→2, 1→3, 3→2, 2→4, the best chain is1→3→2→4(3 hops). A global visited set would mark2as used in the1→2branch and never find the longer chain via3. - Why not caching per user: the best continuation from a user depends on which users are already on the chain, so a per-user cache can return wrong values in cyclic graphs. (Caching is only safe when the graph is acyclic.)
Edge cases follow naturally: no outgoing edges gives 0, a self-follow is skipped, a two-user cycle gives 1, and duplicate pairs just repeat the same branch.
Complexity
- Time: proportional to the number of simple paths explored. This is linear on chains and trees, but exponential in the worst case for dense cyclic graphs, which is inherent to the longest-simple-path problem.
- Space:
O(V + E)for the adjacency map, plusO(V)for the chain set and recursion stack.
Reference solution
from typing import List
def longest_follow_chain(follow_pairs: List[List[int]], start_user: int) -> int:
graph = {}
for follower, followee in follow_pairs:
graph.setdefault(follower, []).append(followee)
def explore(user, on_path):
best = 0
for nxt in graph.get(user, []):
if nxt in on_path:
continue
on_path.add(nxt)
best = max(best, 1 + explore(nxt, on_path))
on_path.remove(nxt)
return best
return explore(start_user, {start_user})