Skip to main content
Back to problems
#1311
Medium Algorithms

Get watched videos by your friends

Array Hash Table Breadth-First Search Graph Theory Sorting
52.1% acceptance
Feb 25, 2026
483
454
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.

Solution

Rust
Time O(n³)
Space O(n)
LeetCode
solution.rs
impl Solution {
  pub fn watched_videos_by_friends(
    watched_videos: Vec<Vec<String>>,
    friends: Vec<Vec<i32>>,
    id: i32,
    level: i32,
  ) -> Vec<String> {
    let n = friends.len();
    let mut visited = vec![false; n];
    let mut queue = std::collections::VecDeque::new();
    queue.push_back(id as usize);
    visited[id as usize] = true;
    let mut cur_level = 0;
    while cur_level < level {
      let sz = queue.len();
      for _ in 0..sz {
        let u = queue.pop_front().unwrap();
        for &v in &friends[u] {
          let v = v as usize;
          if !visited[v] {
            visited[v] = true;
            queue.push_back(v);
          }
        }
      }
      cur_level += 1;
    }
    let mut freq: std::collections::HashMap<String, i32> = std::collections::HashMap::new();
    for &u in &queue {
      for video in &watched_videos[u] {
        *freq.entry(video.clone()).or_insert(0) += 1;
      }
    }
    let mut videos: Vec<(i32, String)> = freq.into_iter().map(|(v, c)| (c, v)).collect();
    videos.sort();
    videos.into_iter().map(|(_, v)| v).collect()
  }
}