Get Watched Videos by Your Friends - Problem

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 & Output

Example 1 — Basic Network
$ Input: watchedVideos = [["A","B"],["C"],["B","C"],["D"]], friends = [[1,2],[0,3],[0,3],[1,2]], id = 0, level = 1
Output: ["B","C"]
💡 Note: Person 0's friends are 1 and 2 (level 1). Person 1 watched ["C"], Person 2 watched ["B","C"]. Video counts: B=1, C=2. Sorted by frequency: ["B","C"]
Example 2 — Level 2 Friends
$ Input: watchedVideos = [["A","B"],["C"],["B","C"],["D"]], friends = [[1,2],[0,3],[0,3],[1,2]], id = 0, level = 2
Output: ["D"]
💡 Note: Person 0's level 2 friends is person 3 (path: 0->1->3 or 0->2->3). Person 3 watched ["D"], so return ["D"]
Example 3 — No Friends at Level
$ Input: watchedVideos = [["A","B"],["C"]], friends = [[1],[0]], id = 0, level = 2
Output: []
💡 Note: Person 0 only has person 1 at level 1. No one exists at level 2, so return empty array

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

Visualization

Tap to expand
Get Watched Videos by Your Friends0["A","B"]1["C"]2["B","C"]3["D"]StartLevel 1Level 1Level 2Level 1 Videos: C (from 1) + B,C (from 2)Count: B=1, C=2Result: ["B", "C"] (sorted by frequency)
Understanding the Visualization
1
Input Network
Graph of people with their watched videos and friend connections
2
BFS Traversal
Use BFS to find people at exact distance (level) from given person
3
Collect & Sort
Count video frequencies from target level people and sort
Key Takeaway
🎯 Key Insight: Use BFS to find exact distances, then count and sort video frequencies from people at target level
Asked in
Facebook 15 Google 12 Amazon 8
28.0K Views
Medium Frequency
~25 min Avg. Time
892 Likes
Ln 1, Col 1
Smart Actions
💡 Explanation
AI Ready
💡 Suggestion Tab to accept Esc to dismiss
// Output will appear here after running code
Code Editor Closed
Click the red button to reopen