Get Watched Videos by Your Friends - Problem
Imagine a social network where everyone watches videos and has friends. You want to discover new content by exploring videos watched by people at different "friendship levels" from you.
Level 1 friends: Your direct friends
Level 2 friends: Friends of your friends
Level k friends: People exactly k friendship connections away from you
Given a person's
Level 1 friends: Your direct friends
Level 2 friends: Friends of your friends
Level k friends: People exactly k friendship connections away from you
Given a person's
id and a target friendship level, return all videos watched by people at that exact level, sorted by frequency (ascending) and alphabetically for ties. This is essentially finding videos in your social network at a specific "distance" using graph traversal! Input & Output
example_1.py โ Basic Social 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,2]. Person 1 watched ["C"], person 2 watched ["B","C"]. Videos: B(1), C(2). Sorted by frequency: ["B","C"]
example_2.py โ 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 are [3]. Person 3 watched ["D"]. Result: ["D"]
example_3.py โ Self (Level 0)
$
Input:
watchedVideos = [["A","B"],["C"],["B","C"],["D"]], friends = [[1,2],[0,3],[0,3],[1,2]], id = 0, level = 0
โบ
Output:
["A","B"]
๐ก Note:
Level 0 means the person themselves. Person 0 watched ["A","B"]. Sorted alphabetically: ["A","B"]
Visualization
Tap to expand
Understanding the Visualization
1
Start at You
Begin BFS from your position (level 0)
2
Find Direct Friends
Explore all your direct friends (level 1)
3
Expand Outward
Continue to friends of friends (level 2, 3, ...)
4
Collect Videos
At target level, gather all videos and sort by frequency
Key Takeaway
๐ฏ Key Insight: BFS naturally explores the graph level by level, making it perfect for finding people at exactly k friendship connections away. This eliminates the need to calculate distances individually and provides optimal performance.
Time & Space Complexity
Time Complexity
O(n + m + v log v)
BFS takes O(n + m) where n is people and m is friendships, plus O(v log v) for sorting videos
โก Linearithmic
Space Complexity
O(n + v)
Queue and visited set take O(n), video frequency map takes O(v)
โก Linearithmic Space
Constraints
- n == friends.length == watchedVideos.length
- 2 โค n โค 100
- 1 โค friends[i].length โค n - 1
- 0 โค friends[i][j] โค n - 1
- 0 โค id < n
- 1 โค level โค n - 1
- All values in friends[i] are unique
- The number of videos watched by each person is at most 100
๐ก
Explanation
AI Ready
๐ก Suggestion
Tab
to accept
Esc
to dismiss
// Output will appear here after running code