Approach
Breadth-first search
For Get Watched Videos by Your Friends, the implementation explores reachable states in layers, which is the standard shape for unweighted shortest paths and minimum-step transitions.
- Model each valid configuration as a state and each legal move as an edge.
- Seed the queue with the starting state and mark it immediately.
- Expand each state once, recording distance or reachability for unseen neighbours.
Code notes
- 30 lines of Java from the credited upstream file 1311.java.
- The implementation visibly relies on sequence storage, hash lookup, ordered lookup, work queue.
- 5 loop blocks detected.
Complexity
Verify that each state and transition is processed only a bounded number of times; that determines the traversal cost.
Check the problem constraints before deciding whether this complexity will pass.
Use this to learn the idea, then write your own version.
1class Solution {2 public List<String> watchedVideosByFriends(List<List<String>> watchedVideos, int[][] friends,3 int id, int level) {4 Queue<Integer> q = new ArrayDeque<>(List.of(id));5 boolean[] seen = new boolean[friends.length];6 seen[id] = true;7 Map<String, Integer> count = new HashMap<>();8 9 for (int i = 0; i < level; ++i)10 for (int sz = q.size(); sz > 0; --sz) {11 for (final int friend : friends[q.peek()])12 if (!seen[friend]) {13 seen[friend] = true;14 q.offer(friend);15 }16 q.poll();17 }18 19 for (final int friend : q)20 for (final String video : watchedVideos.get(friend))21 count.merge(video, 1, Integer::sum);22 23 List<String> ans = new ArrayList<>(count.keySet());24 ans.sort((a, b)25 -> count.get(a).equals(count.get(b)) ? a.compareTo(b)26 : count.get(a).compareTo(count.get(b)));27 return ans;28 }29}30