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.
****
Input: watchedVideos =[["A","B"],["C"],["B","C"],["D"]], friends =[[1,2],[0,3],[0,3],[1,2]], id =0, level =1Output: ["B","C"]Explanation:
You have id =0(green color in the figure) and your friends are(yellow color in the figure):Person with id =1-> watchedVideos =["C"]Person with id =2-> watchedVideos =["B","C"]The frequencies of watchedVideos by your friends are:B ->1C ->2
****
Input: watchedVideos =[["A","B"],["C"],["B","C"],["D"]], friends =[[1,2],[0,3],[0,3],[1,2]], id =0, level =2Output: ["D"]Explanation:
You have id =0(green color in the figure) and the only friend of your friends is the person with id =3(yellow color in the figure).
We need to find all friends at a specific level using BFS (Breadth-First Search) starting from the given person. Then, we collect all videos watched by these friends, count their frequencies, and return the list sorted by frequency and then alphabetically.
classSolution {
funwatchedVideosByFriends(watchedVideos: List<List<String>>, friends: List<List<Int>>, id: Int, level: Int): List<String> {
val n = friends.size
val visited = BooleanArray(n)
var q = mutableListOf(id)
visited[id] = true repeat(level) {
val next = mutableListOf<Int>()
for (u in q) {
for (v in friends[u]) {
if (!visited[v]) {
visited[v] = true next.add(v)
}
}
}
q = next
}
val freq = mutableMapOf<String, Int>()
for (u in q) {
for (vid in watchedVideos[u]) {
freq[vid] = freq.getOrDefault(vid, 0) + 1 }
}
return freq.entries.sortedWith(compareBy({ it.value }, { it.key })).map { it.key }
}
}
⏰ Time complexity: O(n + m log m) — BFS visits each person once (O(n)), and sorting the videos by frequency and name takes O(m log m) where m is the number of unique videos.
🧺 Space complexity: O(n + m) — For visited array, queue, and frequency map.