Talentd
FleetCode
Make and follow sheets.Sign in

Get Watched Videos by Your Friends solution and explanation

MediumArrayBreadth-First SearchGraphHash Table7 min read54.2% acceptanceUpdated 9 Apr 2026
Get Watched Videos by Your Friends | Graphs | Leetcode | DSA | HindiShashCode · 23:33 · 2K viewsWatch on YouTube
7 more videos on this problem
  1. Get Watched Videos by Your Friends | Graphs | Leetcode | DSA | HindiShashCode · 23:33 · 2K views
  2. 1311. Get Watched Videos by Your Friends | LEETCODE MEDIUM | GRAPH | BFS | CODE EXPLAINERcode Explainer · 10:44 · 1K views
  3. Leetcode 1311: Get Watched Videos by Your Friends (Leetcode medium)Algorithms Casts · 18:25 · 760 views
  4. Get Watched Videos by Your Friends (Leetcode 1311)Coding Interviews · 14:23 · 692 views
  5. 【每日一题】1311. Get Watched Videos by Your Friends, 9/4/2020Huifeng Guan · 11:30 · 196 views
  6. Leetcode 1311. Get Watched Videos by Your Friends (bfs)LetsCode · 9:32 · 155 views
  7. Get Watched Videos by Your Friends LeetCodeHustler Den · 3:40 · 86 views
  8. LeetCode 1311: Get Watched Videos by Your FriendsAlitaCode · 28:24 · 7 views

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.

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.

from collections import deque, defaultdict

def getWatchedVideosByFriends(watchedVideos, friends, id, level):
    n = len(watchedVideos)
    queue = deque([id])
    visited = set([id])
    current_level = 0
    
    while queue and current_level < level:
        for _ in range(len(queue)):
            person = queue.popleft()
            for f in friends[person]:
                if f not in visited:
                    visited.add(f)
                    queue.append(f)
        current_level += 1
    
    video_count = defaultdict(int)
    for friend in queue:
        for video in watchedVideos[friend]:
            video_count[video] += 1
    
    return sorted(video_count.keys(), key=lambda x: (video_count[x], x))
function getWatchedVideosByFriends(watchedVideos, friends, id, level) {
    let n = watchedVideos.length;
    let queue = [id];
    let visited = new Set([id]);
    let currentLevel = 0;
    
    while (queue.length && currentLevel < level) {
        let size = queue.length;
        for (let i = 0; i < size; i++) {
            let person = queue.shift();
            for (let f of friends[person]) {
                if (!visited.has(f)) {
                    visited.add(f);
                    queue.push(f);
                }
            }
        }
        currentLevel++;
    }
    
    let videoCount = {};
    for (let friend of queue) {
        for (let video of watchedVideos[friend]) {
            videoCount[video] = (videoCount[video] || 0) + 1;
        }
    }
    
    return Object.keys(videoCount).sort((a, b) => videoCount[a] === videoCount[b] ? a.localeCompare(b) : videoCount[a] - videoCount[b]);
}

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.

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.

import java.util.*;

public class Solution {
    public List<String> getWatchedVideosByFriends(List<List<String>> watchedVideos, List<List<Integer>> friends, int id, int level) {
        Set<Integer> visited = new HashSet<>();
        List<Integer> currLevelFriends = new ArrayList<>();
        dfs(friends, visited, id, level, currLevelFriends);
        Map<String, Integer> videoCount = new HashMap<>();
        
        for (int friendId : currLevelFriends) {
            for (String video : watchedVideos.get(friendId)) {
                videoCount.put(video, videoCount.getOrDefault(video, 0) + 1);
            }
        }
        
        List<String> result = new ArrayList<>(videoCount.keySet());
        result.sort((a, b) -> {
            int comp = Integer.compare(videoCount.get(a), videoCount.get(b));
            if (comp == 0) return a.compareTo(b);
            return comp;
        });
        return result;
    }

    private void dfs(List<List<Integer>> friends, Set<Integer> visited, int current, int level, List<Integer> currLevelFriends) {
        if (level == 0) {
            currLevelFriends.add(current);
            return;
        }
        visited.add(current);
        for (int f : friends.get(current)) {
            if (!visited.contains(f)) {
                dfs(friends, visited, f, level - 1, currLevelFriends);
            }
        }
        visited.remove(current);
    }
}
#include <iostream>
#include <vector>
#include <unordered_set>
#include <unordered_map>
#include <algorithm>

using namespace std;

void dfs(int current, vector<vector<int>>& friends, unordered_set<int>& visited, vector<int>& currLevelFriends, int level) {
    if (level == 0) {
        currLevelFriends.push_back(current);
        return;
    }
    visited.insert(current);
    for (int f : friends[current]) {
        if (!visited.count(f)) {
            dfs(f, friends, visited, currLevelFriends, level - 1);
        }
    }
    visited.erase(current);
}

vector<string> getWatchedVideosByFriends(vector<vector<string>>& watchedVideos, vector<vector<int>>& friends, int id, int level) {
    unordered_set<int> visited;
    vector<int> currLevelFriends;
    dfs(id, friends, visited, currLevelFriends, level);
    
    unordered_map<string, int> videoCount;
    for (int friendId : currLevelFriends) {
        for (string& video : watchedVideos[friendId]) {
            videoCount[video]++;
        }
    }
    
    vector<pair<string, int>> videoList(videoCount.begin(), videoCount.end());
    sort(videoList.begin(), videoList.end(), [](pair<string, int> a, pair<string, int> b) {
        return a.second == b.second ? a.first < b.first : a.second < b.second;
    });
    
    vector<string> result;
    for (auto& p : videoList) {
        result.push_back(p.first);
    }
    return result;
}

This Java method similarly utilizes a recursive DFS approach to gather friends at the required level. It uses a HashSet to track visited friends and a HashMap to count video frequencies, ensuring results are sorted accordingly.

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.

function watchedVideosByFriends(
    watchedVideos: string[][],
    friends: number[][],
    id: number,
    level: number,
): string[] {
    let q: number[] = [id];
    const n: number = friends.length;
    const vis: boolean[] = Array(n).fill(false);
    vis[id] = true;
    while (level-- > 0) {
        const nq: number[] = [];
        for (const i of q) {
            for (const j of friends[i]) {
                if (!vis[j]) {
                    vis[j] = true;
                    nq.push(j);
                }
            }
        }
        q = nq;
    }
    const cnt: { [key: string]: number } = {};
    for (const i of q) {
        for (const v of watchedVideos[i]) {
            cnt[v] = (cnt[v] || 0) + 1;
        }
    }
    const ans: string[] = Object.keys(cnt);
    ans.sort((a, b) => {
        if (cnt[a] === cnt[b]) {
            return a.localeCompare(b);
        }
        return cnt[a] - cnt[b];
    });
    return ans;
}
func watchedVideosByFriends(watchedVideos [][]string, friends [][]int, id int, level int) []string {
	q := []int{id}
	n := len(friends)
	vis := make([]bool, n)
	vis[id] = true
	for level > 0 {
		level--
		nextQ := []int{}
		for _, i := range q {
			for _, j := range friends[i] {
				if !vis[j] {
					vis[j] = true
					nextQ = append(nextQ, j)
				}
			}
		}
		q = nextQ
	}
	cnt := make(map[string]int)
	for _, i := range q {
		for _, v := range watchedVideos[i] {
			cnt[v]++
		}
	}
	ans := []string{}
	for key := range cnt {
		ans = append(ans, key)
	}
	sort.Slice(ans, func(i, j int) bool {
		if cnt[ans[i]] == cnt[ans[j]] {
			return ans[i] < ans[j]
		}
		return cnt[ans[i]] < cnt[ans[j]]
	})
	return ans
}
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–

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

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).

Comments

Now write it yourselfClose this page and solve Get Watched Videos by Your Friends in the editor, without looking.
Practise Get Watched Videos by Your Friends