Problem Description
Given a group of people where each person has a list of watched videos and a list of friends, determine the list of videos watched at a specific friendship level starting from a given person id. Level 1 consists of direct friends, level 2 of friends of friends, and so on. The returned video list should be sorted by frequency (increasing order) and lexicographically if frequencies are equal.
Key Insights
- Utilize Breadth-First Search (BFS) to traverse the friendship graph starting from the given person.
- Track visited persons to avoid cycles in the graph.
- Stop the BFS once the target friendship level is reached.
- Count the frequency of each video from persons at the target level.
- Sort the videos first by frequency and then alphabetically.
Space and Time Complexity
Time Complexity: O(n + m + k log k), where n is the number of persons, m is the number of friendship relationships, and k is the number of unique videos at the target level.
Space Complexity: O(n + v), where n is for BFS queues and visited tracking, and v is for storing video frequency counts.
Solution
We perform a BFS starting from the given person id to the required level, recording each person encountered at that level. Next, we count the frequency of each video that has been watched by these persons. Finally, we return the videos sorted by their frequency (in increasing order) and then by lexicographic order if there is a tie. The solution uses a queue for BFS, a set (or boolean array) for visited nodes, and a hash table (or dictionary/map) for counting video frequencies.
Code Solutions
Below are code solutions in Python, JavaScript, C++, and Java.