|
| 1 | +/** |
| 2 | + * 1311. Get Watched Videos by Your Friends |
| 3 | + * https://leetcode.com/problems/get-watched-videos-by-your-friends/ |
| 4 | + * Difficulty: Medium |
| 5 | + * |
| 6 | + * There are n people, each person has a unique id between 0 and n-1. Given the arrays watchedVideos |
| 7 | + * and friends, where watchedVideos[i] and friends[i] contain the list of watched videos and the |
| 8 | + * list of friends respectively for the person with id = i. |
| 9 | + * |
| 10 | + * Level 1 of videos are all watched videos by your friends, level 2 of videos are all watched |
| 11 | + * videos by the friends of your friends and so on. In general, the level k of videos are all |
| 12 | + * watched videos by people with the shortest path exactly equal to k with you. Given your id |
| 13 | + * and the level of videos, return the list of videos ordered by their frequencies (increasing). |
| 14 | + * For videos with the same frequency order them alphabetically from least to greatest. |
| 15 | + */ |
| 16 | + |
| 17 | +/** |
| 18 | + * @param {string[][]} watchedVideos |
| 19 | + * @param {number[][]} friends |
| 20 | + * @param {number} id |
| 21 | + * @param {number} level |
| 22 | + * @return {string[]} |
| 23 | + */ |
| 24 | +var watchedVideosByFriends = function(watchedVideos, friends, id, level) { |
| 25 | + const visited = new Set([id]); |
| 26 | + let queue = [id]; |
| 27 | + let currentLevel = 0; |
| 28 | + |
| 29 | + while (queue.length && currentLevel < level) { |
| 30 | + const nextQueue = []; |
| 31 | + queue.forEach(person => friends[person].forEach(friend => { |
| 32 | + if (!visited.has(friend)) { |
| 33 | + visited.add(friend); |
| 34 | + nextQueue.push(friend); |
| 35 | + } |
| 36 | + })); |
| 37 | + queue = nextQueue; |
| 38 | + currentLevel++; |
| 39 | + } |
| 40 | + |
| 41 | + const videoFrequency = new Map(); |
| 42 | + queue.forEach(person => watchedVideos[person].forEach(video => { |
| 43 | + return videoFrequency.set(video, (videoFrequency.get(video) || 0) + 1); |
| 44 | + })); |
| 45 | + |
| 46 | + return [...videoFrequency.entries()] |
| 47 | + .sort((a, b) => a[1] === b[1] ? a[0].localeCompare(b[0]) : a[1] - b[1]) |
| 48 | + .map(([video]) => video); |
| 49 | +}; |
0 commit comments