Social Network
Implement follow, unfollow, snapshot, and is_following. The snapshot captures the current state of all relationships and returns an incremental ID starting from 0. is_following must answer whether user A was following user B at a specific past snapshot.
Extend the class with get_followers(user_id, snapshot_id) and get_followees(user_id, snapshot_id), returning the full list of who was following a user, or who a user was following, at any past snapshot.
Add recommend(user_id, snapshot_id, k=5), which returns the top-K users to follow based on friends-of-friends at a given snapshot. A candidate is someone the user doesn’t already follow but is followed by at least one of their followees.
这道题要求设计一个支持版本化查询的社交关系系统:除了基本的关注、取关和快照外,还要能够在任意历史快照中查询“某人是否关注了某人”、某个用户的全部粉丝、以及全部关注对象。进一步还要实现基于“好友的好友”的推荐功能,按历史快照统计候选人的出现次数,返回最值得关注的前 K 个用户。核心难点在于如何高效保存关系的时间版本,通常会用按用户维护的关注 / 粉丝集合,并结合快照编号、时间戳映射或可持久化数据结构来支持历史查询;推荐则需要在指定快照下遍历二跳关系并去重、排除已关注对象,再按频次排序。