[LeetCode] Get Watched Videos by Your Friends

1311. Get Watched Videos by Your Friends

There are n people, each person has a unique id between 0 and n-1. Given the arrays watchedVideos and friends, where watchedVideos[i] and friends[i] contain the list of watched videos and the list of friends respectively for the person with id = i.

Level 1 of videos are all watched videos by your friends, level 2 of videos are all watched videos by the friends of your friends and so on. In general, the level k of videos are all watched videos by people with the shortest path exactly equal to k with you. Given your id and the level of videos, return the list of videos ordered by their frequencies (increasing). For videos with the same frequency order them alphabetically from least to greatest.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
class Solution {
public:
vector<string> watchedVideosByFriends(vector<vector<string>>& watchedVideos, vector<vector<int>>& adj, int id, int level) {
int n = adj.size();
vector<bool> vis(n);
queue<int> q;
q.push(id);
vis[id] = true;
while(level--) {
int sz = q.size();
while(sz--) {
auto u = q.front(); q.pop();
for(auto& v : adj[u]) {
if(!vis[v]) {
vis[v] = true;
q.push(v);
}
}
}
}

vector<pair<int, string>> A;
unordered_map<string, int> mp;
while(!q.empty()) {
auto u = q.front(); q.pop();
for(auto& w : watchedVideos[u])
mp[w]++;
}
for(auto& [k, v] : mp)
A.push_back({v, k});
sort(begin(A), end(A));

vector<string> res;
for(auto& [_, v] : A)
res.push_back(v);
return res;
}
};
Author: Song Hayoung
Link: https://songhayoung.github.io/2022/06/16/PS/LeetCode/get-watched-videos-by-your-friends/
Copyright Notice: All articles in this blog are licensed under CC BY-NC-SA 4.0 unless stating additionally.