LeetCode 1311: Get Watched Videos by Your Friends Solution
Master LeetCode problem 1311 (Get Watched Videos by Your Friends), a medium challenge, with our optimized solutions in Java, C++, and Python. Explore detailed explanations, test your code in our interactive editor, and prepare for coding interviews.
1311. Get Watched Videos by Your Friends
Problem Explanation
Explanation
To solve this problem, we need to find the watched videos by friends up to a certain level of connection. We can achieve this by performing a Breadth First Search (BFS) starting from the person with the given id. We will keep track of the level of each person as we traverse the friends graph. After reaching the specified level, we collect the watched videos of all people at that level and count the frequencies. Finally, we sort the videos first by frequency and then alphabetically.
- Time complexity: O(V + E + nlogn) where V is the number of vertices (people), E is the number of edges (friend connections), and n is the total number of videos watched across all people. The sorting operation dominates the complexity.
- Space complexity: O(V) for maintaining the queue and other data structures.
Solution Code
class Solution {
public List<String> watchedVideosByFriends(List<List<String>> watchedVideos, int[][] friends, int id, int level) {
Map<String, Integer> freqMap = new HashMap<>();
Queue<Integer> queue = new LinkedList<>();
Set<Integer> visited = new HashSet<>();
visited.add(id);
queue.offer(id);
int curLevel = 0;
while (!queue.isEmpty() && curLevel < level) {
int size = queue.size();
for (int i = 0; i < size; i++) {
int curr = queue.poll();
for (int friend : friends[curr]) {
if (!visited.contains(friend)) {
visited.add(friend);
queue.offer(friend);
}
}
}
curLevel++;
}
while (!queue.isEmpty()) {
int curr = queue.poll();
for (String video : watchedVideos.get(curr)) {
freqMap.put(video, freqMap.getOrDefault(video, 0) + 1);
}
}
List<String> result = new ArrayList<>(freqMap.keySet());
Collections.sort(result, (a, b) -> freqMap.get(a).equals(freqMap.get(b)) ? a.compareTo(b) : freqMap.get(a) - freqMap.get(b));
return result;
}
}Try It Yourself
Loading code editor...
Related LeetCode Problems
Frequently Asked Questions
How to solve LeetCode 1311 (Get Watched Videos by Your Friends)?
This page provides optimized solutions for LeetCode problem 1311 (Get Watched Videos by Your Friends) in Java, C++, and Python, along with a detailed explanation and an interactive code editor to test your code.
What is the time complexity of LeetCode 1311 (Get Watched Videos by Your Friends)?
The time complexity for LeetCode 1311 (Get Watched Videos by Your Friends) varies by solution. Check the detailed explanation section for specific complexities in Java, C++, and Python implementations.
Can I run code for LeetCode 1311 on DevExCode?
Yes, DevExCode provides an interactive code editor where you can write, test, and run your code for LeetCode 1311 in Java, C++, or Python.