Get Watched Videos by Your Friends — LeetCode 1311 Python Solution

MediumBreadth-First SearchGraphArrayHash TableSorting
Problem
#1311
Reading time
4 min

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

Python
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

MeasureComplexity
TimeO(n)
SpaceO(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.

Stuck on problems like this in a live interview?

Stealth Interview is a desktop app for macOS and Windows. It reads the problem off your screen and returns a working solution with a step-by-step explanation and its time and space complexity — invisible to screen sharing.

Get Stealth Interview