Get Watched Videos by Your Friends — LeetCode 1311 Python Solution
- Problem
- #1311
- Pattern
- Breadth-First Search
- Reading time
- 4 min
- Source
- leetcode.com
The 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.
Example
- 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):
Python solution
class Solution:
def watchedVideosByFriends(
self,
watchedVideos: List[List[str]],
friends: List[List[int]],
id: int,
level: int,
) -> List[str]:
q = deque([id])
vis = {id}
for _ in range(level):
for _ in range(len(q)):
i = q.popleft()
for j in friends[i]:
if j not in vis:
vis.add(j)
q.append(j)
cnt = Counter()
for i in q:
for v in watchedVideos[i]:
cnt[v] += 1
return sorted(cnt.keys(), key=lambda k: (cnt[k], k))Complexity
| Measure | Complexity |
|---|---|
| Time | O(n) |
| Space | O(n) auxiliary |
Pattern: Breadth-First Search
Expand outward level by level, so the first time you arrive is the shortest way. LeetCode 1311. Get Watched Videos by Your Friends is filed here because LeetCode tags it Breadth-First Search, which is the vocabulary this hub collects.
The breadth-first search guide has the Python template for the pattern and the 233 LeetCode problems that use it.
Related problems
Frequently asked questions
- How hard is LeetCode 1311. Get Watched Videos by Your Friends?
- LeetCode 1311. Get Watched Videos by Your Friends is rated Medium on LeetCode.
- What is the time complexity of LeetCode 1311. Get Watched Videos by Your Friends?
- The Python solution on this page runs in O(n).
- What is the space complexity of LeetCode 1311. Get Watched Videos by Your Friends?
- The Python solution on this page uses O(n) auxiliary space.
- What topics does LeetCode 1311. Get Watched Videos by Your Friends cover?
- LeetCode 1311. Get Watched Videos by Your Friends is tagged Breadth-First Search, Graph, Array, Hash Table and Sorting on LeetCode.