Welcome to Subscribe On Youtube

1311. Get Watched Videos by Your Friends

Description

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. 

 

Example 1:

Input: watchedVideos = [["A","B"],["C"],["B","C"],["D"]], friends = [[1,2],[0,3],[0,3],[1,2]], id = 0, level = 1
Output: ["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 -> 1 
C -> 2

Example 2:

Input: watchedVideos = [["A","B"],["C"],["B","C"],["D"]], friends = [[1,2],[0,3],[0,3],[1,2]], id = 0, level = 2
Output: ["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).

 

Constraints:

  • n == watchedVideos.length == friends.length
  • 2 <= n <= 100
  • 1 <= watchedVideos[i].length <= 100
  • 1 <= watchedVideos[i][j].length <= 8
  • 0 <= friends[i].length < n
  • 0 <= friends[i][j] < n
  • 0 <= id < n
  • 1 <= level < n
  • if friends[i] contains j, then friends[j] contains i

Solutions

BFS.

  • class Solution {
        public List<String> watchedVideosByFriends(
            List<List<String>> watchedVideos, int[][] friends, int id, int level) {
            int n = friends.length;
            boolean[] vis = new boolean[n];
            Deque<Integer> q = new LinkedList<>();
            q.offerLast(id);
            vis[id] = true;
            while (level-- > 0) {
                for (int i = q.size(); i > 0; --i) {
                    int u = q.pollFirst();
                    for (int v : friends[u]) {
                        if (!vis[v]) {
                            q.offerLast(v);
                            vis[v] = true;
                        }
                    }
                }
            }
            Map<String, Integer> freq = new HashMap<>();
            while (!q.isEmpty()) {
                for (String w : watchedVideos.get(q.pollFirst())) {
                    freq.put(w, freq.getOrDefault(w, 0) + 1);
                }
            }
            List<Map.Entry<String, Integer>> t = new ArrayList<>(freq.entrySet());
            t.sort((a, b) -> {
                if (a.getValue() > b.getValue()) {
                    return 1;
                }
                if (a.getValue() < b.getValue()) {
                    return -1;
                }
                return a.getKey().compareTo(b.getKey());
            });
            List<String> ans = new ArrayList<>();
            for (Map.Entry<String, Integer> e : t) {
                ans.add(e.getKey());
            }
            return ans;
        }
    }
    
  • class Solution:
        def watchedVideosByFriends(
            self,
            watchedVideos: List[List[str]],
            friends: List[List[int]],
            id: int,
            level: int,
        ) -> List[str]:
            n = len(friends)
            vis = [False] * n
            q = deque([id])
            vis[id] = True
            for _ in range(level):
                size = len(q)
                for _ in range(size):
                    u = q.popleft()
                    for v in friends[u]:
                        if not vis[v]:
                            q.append(v)
                            vis[v] = True
            freq = Counter()
            for _ in range(len(q)):
                u = q.pop()
                for w in watchedVideos[u]:
                    freq[w] += 1
            videos = list(freq.items())
            videos.sort(key=lambda x: (x[1], x[0]))
            return [v[0] for v in videos]
    
    
  • class Solution {
    public:
        vector<string> watchedVideosByFriends(vector<vector<string>>& watchedVideos, vector<vector<int>>& friends, int id, int level) {
            queue<int> q{ {id} };
            int n = friends.size();
            vector<bool> vis(n);
            vis[id] = true;
            while (level--) {
                for (int k = q.size(); k; --k) {
                    int i = q.front();
                    q.pop();
                    for (int j : friends[i]) {
                        if (!vis[j]) {
                            vis[j] = true;
                            q.push(j);
                        }
                    }
                }
            }
            unordered_map<string, int> cnt;
            while (!q.empty()) {
                int i = q.front();
                q.pop();
                for (const auto& v : watchedVideos[i]) {
                    cnt[v]++;
                }
            }
            vector<string> ans;
            for (const auto& [key, _] : cnt) {
                ans.push_back(key);
            }
            sort(ans.begin(), ans.end(), [&cnt](const string& a, const string& b) {
                return cnt[a] == cnt[b] ? a < b : cnt[a] < cnt[b];
            });
            return ans;
        }
    };
    
    
  • func watchedVideosByFriends(watchedVideos [][]string, friends [][]int, id int, level int) []string {
    	q := []int{id}
    	n := len(friends)
    	vis := make([]bool, n)
    	vis[id] = true
    	for level > 0 {
    		level--
    		nextQ := []int{}
    		for _, i := range q {
    			for _, j := range friends[i] {
    				if !vis[j] {
    					vis[j] = true
    					nextQ = append(nextQ, j)
    				}
    			}
    		}
    		q = nextQ
    	}
    	cnt := make(map[string]int)
    	for _, i := range q {
    		for _, v := range watchedVideos[i] {
    			cnt[v]++
    		}
    	}
    	ans := []string{}
    	for key := range cnt {
    		ans = append(ans, key)
    	}
    	sort.Slice(ans, func(i, j int) bool {
    		if cnt[ans[i]] == cnt[ans[j]] {
    			return ans[i] < ans[j]
    		}
    		return cnt[ans[i]] < cnt[ans[j]]
    	})
    	return ans
    }
    
    
  • function watchedVideosByFriends(
        watchedVideos: string[][],
        friends: number[][],
        id: number,
        level: number,
    ): string[] {
        let q: number[] = [id];
        const n: number = friends.length;
        const vis: boolean[] = Array(n).fill(false);
        vis[id] = true;
        while (level-- > 0) {
            const nq: number[] = [];
            for (const i of q) {
                for (const j of friends[i]) {
                    if (!vis[j]) {
                        vis[j] = true;
                        nq.push(j);
                    }
                }
            }
            q = nq;
        }
        const cnt: { [key: string]: number } = {};
        for (const i of q) {
            for (const v of watchedVideos[i]) {
                cnt[v] = (cnt[v] || 0) + 1;
            }
        }
        const ans: string[] = Object.keys(cnt);
        ans.sort((a, b) => {
            if (cnt[a] === cnt[b]) {
                return a.localeCompare(b);
            }
            return cnt[a] - cnt[b];
        });
        return ans;
    }
    
    

All Problems

All Solutions