# 1311. Get Watched Videos by Your Friends¶

• Time:
• Space:
  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 class Solution { public: vector watchedVideosByFriends(vector>& watchedVideos, vector>& friends, int id, int level) { vector ans; vector visited(friends.size()); visited[id] = true; queue queue{{id}}; unordered_map count; set> freqAndVideo; for (int i = 0; i < level; ++i) for (int j = queue.size(); j > 0; --j) { for (int f : friends[queue.front()]) if (visited[f] == false) { visited[f] = true; queue.push(f); } queue.pop(); } for (int i = queue.size(); i > 0; --i) { for (const string& video : watchedVideos[queue.front()]) ++count[video]; queue.pop(); } for (const auto& [video, freq] : count) freqAndVideo.insert({freq, video}); for (const auto& [_, video] : freqAndVideo) ans.push_back(video); return ans; } }; 
  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 class Solution { public List watchedVideosByFriends(List> watchedVideos, int[][] friends, int id, int level) { boolean[] visited = new boolean[friends.length]; visited[id] = true; Queue queue = new ArrayDeque<>(Arrays.asList(id)); Map count = new HashMap<>(); for (int i = 0; i < level; ++i) for (int j = queue.size(); j > 0; --j) { for (int friend : friends[queue.peek()]) if (visited[friend] == false) { visited[friend] = true; queue.add(friend); } queue.poll(); } for (int friend : queue) for (final String video : watchedVideos.get(friend)) count.merge(video, 1, Integer::sum); List ans = new ArrayList<>(count.keySet()); ans.sort((a, b) -> count.get(a) == count.get(b) ? a.compareTo(b) : count.get(a) - count.get(b)); return ans; } } 
  1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 class Solution: def watchedVideosByFriends(self, watchedVideos: List[List[str]], friends: List[List[int]], id: int, level: int) -> List[str]: visited = [False] * 100 visited[id] = True q = collections.deque([id]) count = collections.Counter() for _ in range(level): for _ in range(len(q)): curr = q.popleft() for friend in friends[curr]: if not visited[friend]: visited[friend] = True q.append(friend) for friend in q: for video in watchedVideos[friend]: count[video] += 1 return sorted(count.keys(), key=lambda video: (count[video], video))