Skip to main content

Get Watched Videos by Your Friends - Solution & Explanation

MediumArrayHash TableBreadth-First SearchGraph15 min readAsked at: Amazon, Bolt, Guidewire
Practice this problem

Problem Statement

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. 

 

Example 1:

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):
Person with id = 1 -> watchedVideos = ["C"] 
Person with id = 2 -> watchedVideos = ["B","C"] 
The frequencies of watchedVideos by your friends are: 
B -> 1 
C -> 2

Example 2:

Input: watchedVideos = [["A","B"],["C"],["B","C"],["D"]], friends = [[1,2],[0,3],[0,3],[1,2]], id = 0, level = 2
Output: ["D"]
Explanation: 
You have id = 0 (green color in the figure) and the only friend of your friends is the person with id = 3 (yellow color in the figure).

 

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
  • if friends[i] contains j, then friends[j] contains i

Approach Overview

Problem Overview: You are given a social network where each person has a list of watched videos and a list of friends. Starting from a specific person id, find all friends exactly level connections away, collect the videos they watched, and return them sorted by frequency and then lexicographically.

Approach 1: Breadth-First Search (BFS) on Graph (O(n + m + k log k) time, O(n + k) space)

Treat the friendship list as an adjacency list of an unweighted graph. Run Breadth-First Search starting from the given id. BFS naturally explores nodes level by level, so you stop expanding once you reach the required distance. Use a queue to process users and a visited set to avoid revisiting nodes. After reaching the target level, iterate through those friends and aggregate their watched videos in a frequency map (hash table).

Once the counts are collected, convert the map into a list of video titles and sort it. The sorting rule is key: first by frequency (ascending), then by video name (lexicographically). This is typically implemented using a custom comparator or sorting key. BFS ensures you only traverse each friend once, giving O(n + m) traversal time where n is users and m is friendship edges. The final sorting step dominates when many videos are collected, giving O(k log k) where k is the number of distinct videos.

Approach 2: Depth-First Search (DFS) with Level Tracking (O(n + m + k log k) time, O(n + k) space)

An alternative is a recursive DFS that tracks the current depth from the starting user. The recursion explores neighbors until the depth equals the target level. At that point, instead of continuing deeper, collect the watched videos of that friend. A visited array or set prevents infinite loops in cyclic friendships.

DFS works because you explicitly track depth in the recursive calls. However, it tends to explore deeper paths earlier and may visit unnecessary branches before reaching the correct level. You still use a hash table (hash table) to count video frequencies and apply the same sorting rule at the end. While the asymptotic complexity matches BFS, the control flow is less intuitive for level-based queries.

Recommended for interviews: BFS is the expected solution. The problem explicitly asks for friends at a specific distance in a graph, which is exactly what BFS is designed for. Implementing BFS with a queue, visited set, frequency map, and final sort demonstrates solid understanding of graph traversal and practical data structure usage.

Approach 1: Breadth-First Search (BFS)

This approach leverages BFS to traverse the friends network layer by layer starting from the given person ID. We only consider the friends at the exact level specified and grab their watched videos to determine the output.

The above Python function first initializes a queue and a visited set to perform BFS starting from the given 'id'. We iterate level by level until the desired 'level' is reached, updating the queue with each friend's friends. Once the desired level is reached, we tally the frequency of each video watched by those on that level and sort them first by frequency, then by alphabetical order.

Code

Python

JavaScript

Complexity

Time Complexity: O(n + v log v) where 'n' is the number of nodes and 'v' is the number of videos.
Space Complexity: O(n + v) where 'v' is for storing video frequencies.

Try this approach in the editor →

Approach 2: Depth-First Search (DFS)

This approach uses DFS to traverse the social network to find friends at the given level. It uses recursion to explore each friend's connections until reaching the desired depth. Then, collects and sorts videos watched by the friends at that level.

This C++ function uses recursive DFS to find friends exactly at the specified level away from the starting ID. It maintains a visited set to handle cycles and uses an unordered map to count video frequencies. Finally, it sorts results by frequency and name.

Code

C++

Java

Complexity

Time Complexity: O(n^2 + v log v) where 'n' is the number of people and 'v' is the number of different videos.
Space Complexity: O(n + v) to store visited nodes and video frequency counts.

Try this approach in the editor →

Approach 3: BFS

We can use the Breadth-First Search (BFS) method to start from id and find all friends at a distance of level, then count the videos watched by these friends.

Specifically, we can use a queue q to store the friends at the current level. Initially, add id to the queue q. Use a hash table or a boolean array vis to record the friends that have already been visited. Then, perform level iterations, in each iteration dequeue all friends from the queue and enqueue their friends until all friends at distance level are found.

Next, we use a hash table cnt to count the videos watched by these friends and their frequencies. Finally, sort the key-value pairs in the hash table in ascending order by frequency, and if frequencies are the same, sort by video name in ascending order. Return the sorted list of video names.

Time complexity is O(n + m + v times log v), and space complexity is O(n + v). Here, n and m are the lengths of the arrays watchedVideos and friends, respectively, and v is the total number of videos watched by all friends.

Code

Python

Java

C++

Go

TypeScript

Try this approach in the editor →

Complexity Comparison

ApproachComplexity
Breadth-First Search (BFS)

Time Complexity: O(n + v log v) where 'n' is the number of nodes and 'v' is the number of videos.
Space Complexity: O(n + v) where 'v' is for storing video frequencies.

Depth-First Search (DFS)

Time Complexity: O(n^2 + v log v) where 'n' is the number of people and 'v' is the number of different videos.
Space Complexity: O(n + v) to store visited nodes and video frequency counts.

BFS—

Detailed Complexity Analysis

ApproachTimeSpaceWhen to Use
Breadth-First Search (BFS)O(n + m + k log k)O(n + k)Best for level-based traversal in graphs; naturally finds nodes at exact distance
Depth-First Search (DFS) with Level TrackingO(n + m + k log k)O(n + k)Useful when recursion is preferred or when exploring graph paths with explicit depth control

Video Solution

Get Watched Videos by Your Friends | Graphs | Leetcode | DSA | Hindi • ShashCode • 2,849 views views

Watch 7 more video solutions →

Frequently Asked Questions

Is Get Watched Videos by Your Friends easy or hard?
The problem is rated Medium on LeetCode. The BFS traversal itself is straightforward, but combining graph traversal, frequency counting, and custom sorting makes it slightly more involved than basic graph problems.
Get Watched Videos by Your Friends Python/Java solution
A typical Python or Java solution performs BFS from the starting user until the target level is reached. Then it aggregates watched videos using a hash map and sorts the results with a custom comparator based on frequency and lexicographic order.
How to solve Get Watched Videos by Your Friends in O(n)?
Graph traversal to reach the required friend level runs in O(n + m) using BFS. However, the final step requires sorting videos by frequency and lexicographic order, which adds O(k log k) time. Because of this sorting requirement, the complete solution cannot be strictly O(n).
What is the best approach for Get Watched Videos by Your Friends?
Breadth-First Search (BFS) is the best approach because the problem asks for friends at an exact distance in a social graph. BFS naturally explores nodes level by level, making it easy to stop when the target level is reached. After collecting those friends, count video frequencies using a hash map and sort the results by frequency and lexicographic order.
Is Get Watched Videos by Your Friends asked at Google/Amazon/Meta?
Graph traversal and BFS problems like this frequently appear in interviews at companies such as Amazon, Google, and Meta. Variations involving social networks, level traversal, and frequency counting are common patterns used to test graph fundamentals and data structure skills.
What data structure is used in Get Watched Videos by Your Friends?
The main data structures are a queue for BFS traversal, a visited set or boolean array to avoid revisiting users, and a hash map to count video frequencies. After counting, a list or array is used for sorting the video titles according to the problem's ordering rules.
What is the time complexity of Get Watched Videos by Your Friends?
The overall time complexity is O(n + m + k log k). BFS traversal of the friendship graph takes O(n + m), where n is the number of users and m is the number of friendships. Counting videos takes O(k), and sorting the distinct video titles by frequency and name costs O(k log k).

Ready to solve this problem?

Practice Get Watched Videos by Your Friends with our built-in code editor and test cases.

Practice on FleetCode