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
- 38 lines of C++ from the credited upstream file 1311.cpp.
- The implementation visibly relies on sequence storage, hash lookup, ordered lookup, work queue.
- 7 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:3 vector<string> watchedVideosByFriends(vector<vector<string>>& watchedVideos,4 vector<vector<int>>& friends, int id,5 int level) {6 vector<string> ans;7 queue<int> q{{id}};8 vector<bool> seen(friends.size());9 seen[id] = true;10 unordered_map<string, int> count;11 set<pair<int, string>> freqAndVideo;12 13 for (int i = 0; i < level; ++i)14 for (int sz = q.size(); sz > 0; --sz) {15 for (const int friend_ : friends[q.front()])16 if (!seen[friend_]) {17 seen[friend_] = true;18 q.push(friend_);19 }20 q.pop();21 }22 23 for (int i = q.size(); i > 0; --i) {24 for (const string& video : watchedVideos[q.front()])25 ++count[video];26 q.pop();27 }28 29 for (const auto& [video, freq] : count)30 freqAndVideo.insert({freq, video});31 32 for (const auto& [_, video] : freqAndVideo)33 ans.push_back(video);34 35 return ans;36 }37};38