Get Watched Videos by Your Friends
The problem can be solved using Breadth-First Search (BFS) to find friends at a given level and then collecting and sorting the videos based on the frequency.
Here’s a code to implement the logic:
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
| from collections import Counter, deque
class Solution:
def watchedVideosByFriends(self, watchedVideos: List[List[str]], friends: List[List[int]], id: int, level: int) -> List[str]:
# Using BFS to find friends at the given level
visited = [False] * len(friends)
visited[id] = True
queue = deque([id])
while level > 0:
for i in range(len(queue)):
current = queue.popleft()
for friend in friends[current]:
if not visited[friend]:
visited[friend] = True
queue.append(friend)
level -= 1
# Collecting videos watched by friends at the given level
videos = []
for person in queue:
videos += watchedVideos[person]
# Counting the frequency of the videos and sorting based on frequency and then lexicographically
frequency = Counter(videos)
result = sorted(frequency.keys(), key=lambda x: (frequency[x], x))
return result
|
The code first uses BFS to find friends at the given level. Then, it collects all the videos watched by those friends and counts their frequency using the Counter class from the collections module. Finally, the videos are sorted by their frequencies, and for videos with the same frequency, they are sorted lexicographically.