Versioned Friend Recommendations
Learn this problemProblem statement
A directed social graph has n users numbered from 0 to n - 1. A relationship u -> v means that user u follows user v.
Process relationship updates, immutable snapshots, and historical recommendation queries. Every snapshot includes all earlier updates, and later updates never change an earlier snapshot.
Operations
FOLLOW u vactivatesu -> v. The relationship is inactive immediately before the command.UNFOLLOW u vdeactivatesu -> v. The relationship is active immediately before the command.SNAPSHOTcreates the next snapshot. IDs start at0. Append the ID as a decimal string.RECOMMEND user snapshot_id kappends up tokrecommendations computed from that snapshot.
Recommendation Rule
A candidate must be different from user, must not already be followed by user, and must be reachable by at least one two-hop path user -> middle -> candidate at the requested snapshot.
The candidate's score is the number of distinct active middle users that form such a path. Rank candidates by score descending, then user ID ascending. Return the first k candidate IDs.
Serialize each recommendation list as a string containing IDs inside brackets, separated by commas and no spaces. Serialize an empty list as []. Only SNAPSHOT and RECOMMEND produce output. Return those strings in command order.
Historical Storage
For this exercise, assume each directed relationship is stored as a change history and the whole graph is not copied for each snapshot. Use binary search on that authored history and a bounded heap for recommendation selection.
Function
recommendAtSnapshots(n: int, operations: String[]) → String[]Examples
Example 1
n = 5operations = ["FOLLOW 0 1","FOLLOW 0 2","FOLLOW 1 3","FOLLOW 2 3","FOLLOW 2 4","SNAPSHOT","RECOMMEND 0 0 2"]return = ["0","[3,4]"]User 3 has score 2 through middle users 1 and 2. User 4 has score 1 through user 2.
Example 2
n = 6operations = ["FOLLOW 0 1","FOLLOW 0 2","FOLLOW 1 3","FOLLOW 2 4","SNAPSHOT","RECOMMEND 0 0 5"]return = ["0","[3,4]"]Users 3 and 4 each have score 1. The smaller user ID breaks the tie.
Example 3
n = 5operations = ["FOLLOW 0 1","FOLLOW 1 2","SNAPSHOT","FOLLOW 0 2","FOLLOW 1 3","SNAPSHOT","RECOMMEND 0 0 3","RECOMMEND 0 1 3"]return = ["0","1","[2]","[3]"]At snapshot 0, user 2 is a two-hop candidate. At snapshot 1, user 0 already follows 2, so 2 is excluded and 3 is recommended.
Constraints
1 <= n <= 5001 <= operations.length <= 10000- There are at most
200RECOMMENDcommands. 0 <= u, v, user < nandu != v1 <= k <= n- Every
FOLLOWtargets an inactive relationship. - Every
UNFOLLOWtargets an active relationship. - Every recommendation references a snapshot that has already been created.
- Commands contain single spaces between tokens.
- At least one command produces output.