#1311

Get Watched Videos by Your Friends

Medium
ArrayHash TableBreadth-First SearchGraph TheorySortingHash MapArray
LeetCode ↗

Approaches

Brute ForceOptimal
Complexity Comparison
Brute ForceOptimal Solution
Time
O(n²)
O(n)
Space
O(1)
O(n)
💡

Intuition

Time O(n)Space O(n)

The optimal approach uses BFS to efficiently traverse the friends' network and gather videos watched at the specified level. This method minimizes unnecessary checks and leverages data structures for quick lookups.

⚙️

Algorithm

3 steps
  1. 1Step 1: Initialize a queue for BFS and a set to track visited nodes.
  2. 2Step 2: Perform BFS until reaching the desired level, collecting friends at that level.
  3. 3Step 3: Count the frequency of videos watched by those friends and sort the results.
solution.py27 lines
1# Full working Python code
2from collections import defaultdict, deque
3
4def watchedVideosByFriends(watchedVideos, friends, id, level):
5    queue = deque([id])
6    visited = set([id])
7    current_level = 0
8    video_count = defaultdict(int)
9
10    while queue:
11        if current_level == level:
12            break
13        for _ in range(len(queue)):
14            person = queue.popleft()
15            for friend in friends[person]:
16                if friend not in visited:
17                    visited.add(friend)
18                    queue.append(friend)
19        current_level += 1
20
21    while queue:
22        person = queue.popleft()
23        for video in watchedVideos[person]:
24            video_count[video] += 1
25
26    result = sorted(video_count.items(), key=lambda x: (x[1], x[0]))
27    return [video for video, _ in result]

Complexity note: The time complexity is O(n) because we traverse each friend and their videos only once, making it efficient for larger datasets.

  • 1Understanding BFS is crucial for traversing friend networks effectively.
  • 2Using data structures like HashMap can significantly simplify counting and sorting tasks.

Solutions and explanations are original Tejav content. Problem titles © LeetCode — use the LeetCode button above for the full problem statement.