Problem 1311

Abstract / Summary

Given a list of friends and their watched videos, return all unique videos watched by any of your friends.

Note

The full problem description, including helpful examples, can be found on LeetCode.

Python 1311.py

class Solution:
    def watchedVideosByFriends(self, watchedVideos: List[List[str]], friends: List[List[int]], id: int, level: int) -> List[str]:
        todo = set([ id ]) # my own ID
        seen = set()
        # basic BFS search
        for distance in range(1, level + 1):
            next = []
            for t in todo:
                seen.add(t)
                next += friends[t]
            todo = set(next) - seen

        # enumerate videos of friends at final level
        videos = defaultdict(int)
        for t in todo:
            for v in watchedVideos[t]:
                videos[v] += 1

        # least watched videos first, then ordered by name
        return sorted([ name for name, count in videos.items() ], key = lambda x : ( videos[x], x) )
20 lines | 788 bytes | submitted May 11, 2024 | GitHub   26% comment ratio | tab size 4 | low complexity

Difficulty

This problem is ranked as
easy medium hard

and has an acceptance rate of about 54% (80k+ submissions).

Typical patterns to solve this problem:
  • Array
  • Breadth First Search
  • Graph Theory
  • Hash Table
  • Sorting
I solved 663 easy, 1250 medium and 309 hard problems

AI Disclaimer

Every single line of code was written by me, 100% from scratch, between August 2023 and August 2024.
However, two years later I set up this website and used various AI tools to generate most of the walkthrough / explanations below.

See this dedicated page for more details.
LeetCode profile | GitHub repo

Code Walkthrough

Overview

The implementation solves the problem of retrieving videos watched by friends at a specific friendship distance. It conducts a breadth-first search (BFS) from the target user, isolates the friends that lie exactly level edges away, aggregates the videos they have watched, and finally returns the video titles ordered first by frequency and then alphabetically.

Key Steps

Initialize BFS structures

todo = set([id])          # start from the target user
seen = set()              # tracks users already processed

The todo set holds the frontier of users to explore at the current distance, while seen prevents revisiting users that have already been expanded.

Perform level-by-level expansion

for distance in range(1, level + 1):
    next = []
    for t in todo:
        seen.add(t)
        next += friends[t]
    todo = set(next) - seen

The outer loop iterates exactly level times, advancing the frontier one friendship hop per iteration. Inside, each user t in the current frontier is marked as processed, and all of their direct friends are appended to a temporary list next. Converting next to a set removes duplicate entries that can arise from multiple paths to the same friend, and subtracting seen eliminates any user that has already been visited, guaranteeing that todo always contains only the nodes at the exact current distance.

Collect video frequencies

videos = defaultdict(int)
for t in todo:
    for v in watchedVideos[t]:
        videos[v] += 1

After the BFS finishes, todo contains precisely the friends at the required distance. The nested loops walk through each of those friends and increment a counter for every video title they have watched. The defaultdict(int) automatically creates a zero entry for unseen titles, simplifying the counting logic.

Sort result

return sorted(
    [name for name, count in videos.items()],
    key=lambda x: (videos[x], x)
)

The final list comprehension extracts just the video names from the frequency map. The sorted call uses a key function that first looks up the frequency (videos[x]) and then the name itself, ensuring that titles with lower watch counts appear earlier, and ties are broken alphabetically.

Edge Cases Handled

The code gracefully manages several boundary conditions without additional checks. When a user has no friends, the BFS frontier becomes empty after the first iteration, and the subsequent counting loop simply yields an empty result. If the requested level is zero, the outer loop does not execute, leaving todo as the set containing only the original id. Consequently, the function returns the videos watched by the target user themselves, which aligns with the natural interpretation of “distance zero.”

Cycles in the friendship graph are neutralized by the seen set; once a user is added to seen, any later encounter through another path is ignored, preventing infinite loops. Duplicate friendships (e.g., a friend appearing multiple times in a list) are collapsed by converting the next list to a set before subtraction, ensuring each user is processed at most once per level. Empty watchedVideos entries for a friend simply result in no increments to the videos map, leaving the final ordering unaffected.

Performance Optimizations

The algorithm leverages set operations to keep the BFS frontier compact and free of duplicates, which reduces the amount of work in each iteration. By maintaining a separate seen collection, it avoids redundant expansions of already visited nodes, cutting down unnecessary neighbor traversals.

Using defaultdict(int) for the video frequency map eliminates the need for explicit existence checks before incrementing counters, streamlining the inner counting loop.

The final sorting step accesses the pre-computed frequency dictionary directly inside the key lambda, avoiding repeated lookups or auxiliary data structures. This direct reference pattern contributes to a tighter runtime during the ordering phase.

written by openai gpt

ELI5 - Simplified Explanation

Imagine that everyone in a big group is standing in a giant web of friendships. You are starting at one person who has a specific number. The goal is to walk out to a certain distance to find all the friends who are exactly that far away from you.

First, think about taking steps one at a time. To find the friends at the right distance, there is a way to keep track of who has already been visited so nobody gets counted twice. You start with just the person you are looking for, and then you look at all of their friends, then all of their friends' friends, and so on until the right distance is reached. Think of this like ripples in a pond moving outward from a stone.

Once that exact distance is reached, you look at the list of videos that each of those specific friends has watched. You make a big pile where you write down the name of every video found and count how many times each one appears. If five people watched the same cartoon, that video gets five points.

Finally, the videos are sorted. The videos that were watched by the fewest people go at the front of the line. If two videos have the same number of counts, the names are sorted alphabetically, like how words appear in a dictionary. This helps everyone see which videos are the least popular among that group of friends.

written by google gemini

Code Quality

Several LLMs ranked my code quality on a scale from 1 (very poor) to 10 (outstanding):
n = 27 | median = 7 | μ = 7.30 | σ = 0.85

Complexity Analysis

not analyzed yet

Other Solutions

I wrote a basic crawler to find other solutions to that problem.
Obviously, I did that after I solved the problem myself.

In general, AlgoMonster and WalkCCC solutions are high-quality and always worth a look.
I haven't checked most of the other solutions, but they might be helpful as well.

And of course, the LeetCode forum is always a good place (or even the best) to look for alternative approaches.

(click on a column header to sort the table)
author
author solutions
www AlgoMonster C++ Python Java TS
WalkCCC C++ Python Java
leetcode.ca C++ Python Java Go TS
Progiez C++ Python Java
github black-shadows C++
charles-wangkai Java
fsq C++
JoshCrozier JS
lkwq007 Python
suxrobGM C#
wisdompeak C++
YuriSpiridonov Python
AlgoMonster C++, Python, Java, TypeScript
WalkCCC C++, Python, Java
leetcode.ca C++, Go, Java, Python, TypeScript
Progiez C++, Java, Python
black-shadows C++, C++
charles-wangkai Java
fsq C++
JoshCrozier JavaScript
lkwq007 Python
suxrobGM C#
wisdompeak C++
YuriSpiridonov Python
23 links | 12 authors | 7 languages

Videos

3 videos   did my crawler come up with invalid videos ? drop me a line.

Extra

There are a few extra pages giving you some insights into my setup:
  • Tech Stack - my development environment and tools
  • AI - how AI helped me create this website (NOT solving the problems)
  • Progress - progression over time
  • Quality - code quality