Off-by-one on range boundaries
Wrong move: Loop endpoints miss first/last candidate.
Usually fails on: Fails on minimal arrays and exact-boundary answers.
Fix: Re-derive loops from inclusive/exclusive ranges before coding.
Move from brute-force thinking to an efficient approach using array strategy.
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.
Example 1:
Input: watchedVideos = [["A","B"],["C"],["B","C"],["D"]], friends = [[1,2],[0,3],[0,3],[1,2]], id = 0, level = 1 Output: ["B","C"] Explanation: You have id = 0 (green color in the figure) and your friends are (yellow color in the figure): Person with id = 1 -> watchedVideos = ["C"] Person with id = 2 -> watchedVideos = ["B","C"] The frequencies of watchedVideos by your friends are: B -> 1 C -> 2
Example 2:
Input: watchedVideos = [["A","B"],["C"],["B","C"],["D"]], friends = [[1,2],[0,3],[0,3],[1,2]], id = 0, level = 2 Output: ["D"] Explanation: You have id = 0 (green color in the figure) and the only friend of your friends is the person with id = 3 (yellow color in the figure).
Constraints:
n == watchedVideos.length == friends.length2 <= n <= 1001 <= watchedVideos[i].length <= 1001 <= watchedVideos[i][j].length <= 80 <= friends[i].length < n0 <= friends[i][j] < n0 <= id < n1 <= level < nfriends[i] contains j, then friends[j] contains iProblem summary: 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.
Start with the most direct exhaustive search. That gives a correctness anchor before optimizing.
Pattern signal: Array · Hash Map
[["A","B"],["C"],["B","C"],["D"]] [[1,2],[0,3],[0,3],[1,2]] 0 1
[["A","B"],["C"],["B","C"],["D"]] [[1,2],[0,3],[0,3],[1,2]] 0 2
Source-backed implementations are provided below for direct study and interview prep.
// Accepted solution for LeetCode #1311: Get Watched Videos by Your Friends
class Solution {
public List<String> watchedVideosByFriends(
List<List<String>> watchedVideos, int[][] friends, int id, int level) {
Deque<Integer> q = new ArrayDeque<>();
q.offer(id);
int n = friends.length;
boolean[] vis = new boolean[n];
vis[id] = true;
while (level-- > 0) {
for (int k = q.size(); k > 0; --k) {
int i = q.poll();
for (int j : friends[i]) {
if (!vis[j]) {
vis[j] = true;
q.offer(j);
}
}
}
}
Map<String, Integer> cnt = new HashMap<>();
for (int i : q) {
for (var v : watchedVideos.get(i)) {
cnt.merge(v, 1, Integer::sum);
}
}
List<String> ans = new ArrayList<>(cnt.keySet());
ans.sort((a, b) -> {
int x = cnt.get(a), y = cnt.get(b);
return x == y ? a.compareTo(b) : Integer.compare(x, y);
});
return ans;
}
}
// Accepted solution for LeetCode #1311: Get Watched Videos by Your Friends
func watchedVideosByFriends(watchedVideos [][]string, friends [][]int, id int, level int) []string {
q := []int{id}
n := len(friends)
vis := make([]bool, n)
vis[id] = true
for level > 0 {
level--
nextQ := []int{}
for _, i := range q {
for _, j := range friends[i] {
if !vis[j] {
vis[j] = true
nextQ = append(nextQ, j)
}
}
}
q = nextQ
}
cnt := make(map[string]int)
for _, i := range q {
for _, v := range watchedVideos[i] {
cnt[v]++
}
}
ans := []string{}
for key := range cnt {
ans = append(ans, key)
}
sort.Slice(ans, func(i, j int) bool {
if cnt[ans[i]] == cnt[ans[j]] {
return ans[i] < ans[j]
}
return cnt[ans[i]] < cnt[ans[j]]
})
return ans
}
# Accepted solution for LeetCode #1311: Get Watched Videos by Your Friends
class Solution:
def watchedVideosByFriends(
self,
watchedVideos: List[List[str]],
friends: List[List[int]],
id: int,
level: int,
) -> List[str]:
q = deque([id])
vis = {id}
for _ in range(level):
for _ in range(len(q)):
i = q.popleft()
for j in friends[i]:
if j not in vis:
vis.add(j)
q.append(j)
cnt = Counter()
for i in q:
for v in watchedVideos[i]:
cnt[v] += 1
return sorted(cnt.keys(), key=lambda k: (cnt[k], k))
// Accepted solution for LeetCode #1311: Get Watched Videos by Your Friends
struct Solution;
use std::collections::HashMap;
use std::collections::VecDeque;
impl Solution {
fn watched_videos_by_friends(
watched_videos: Vec<Vec<String>>,
friends: Vec<Vec<i32>>,
id: i32,
level: i32,
) -> Vec<String> {
let n = watched_videos.len();
let mut visited = vec![false; n];
let mut queue: VecDeque<(usize, i32)> = VecDeque::new();
let id = id as usize;
visited[id] = true;
queue.push_back((id, 0));
let mut freq: HashMap<String, usize> = HashMap::new();
while let Some((u, l)) = queue.pop_front() {
if l < level {
for &friend in &friends[u] {
let v = friend as usize;
if !visited[v] {
visited[v] = true;
queue.push_back((v, l + 1));
}
}
} else {
for video in &watched_videos[u] {
*freq.entry(video.to_string()).or_default() += 1;
}
}
}
let mut pairs: Vec<(usize, String)> = vec![];
for (video, count) in freq {
pairs.push((count, video));
}
pairs.sort_unstable();
pairs.into_iter().map(|p| p.1).collect()
}
}
#[test]
fn test() {
let watched_videos = vec_vec_string![["A", "B"], ["C"], ["B", "C"], ["D"]];
let friends = vec_vec_i32![[1, 2], [0, 3], [0, 3], [1, 2]];
let id = 0;
let level = 1;
let res = vec_string!["B", "C"];
assert_eq!(
Solution::watched_videos_by_friends(watched_videos, friends, id, level),
res
);
let watched_videos = vec_vec_string![["A", "B"], ["C"], ["B", "C"], ["D"]];
let friends = vec_vec_i32![[1, 2], [0, 3], [0, 3], [1, 2]];
let id = 0;
let level = 2;
let res = vec_string!["D"];
assert_eq!(
Solution::watched_videos_by_friends(watched_videos, friends, id, level),
res
);
}
// Accepted solution for LeetCode #1311: Get Watched Videos by Your Friends
function watchedVideosByFriends(
watchedVideos: string[][],
friends: number[][],
id: number,
level: number,
): string[] {
let q: number[] = [id];
const n: number = friends.length;
const vis: boolean[] = Array(n).fill(false);
vis[id] = true;
while (level-- > 0) {
const nq: number[] = [];
for (const i of q) {
for (const j of friends[i]) {
if (!vis[j]) {
vis[j] = true;
nq.push(j);
}
}
}
q = nq;
}
const cnt: { [key: string]: number } = {};
for (const i of q) {
for (const v of watchedVideos[i]) {
cnt[v] = (cnt[v] || 0) + 1;
}
}
const ans: string[] = Object.keys(cnt);
ans.sort((a, b) => {
if (cnt[a] === cnt[b]) {
return a.localeCompare(b);
}
return cnt[a] - cnt[b];
});
return ans;
}
Use this to step through a reusable interview workflow for this problem.
Two nested loops check every pair or subarray. The outer loop fixes a starting point, the inner loop extends or searches. For n elements this gives up to n²/2 operations. No extra space, but the quadratic time is prohibitive for large inputs.
Most array problems have an O(n²) brute force (nested loops) and an O(n) optimal (single pass with clever state tracking). The key is identifying what information to maintain as you scan: a running max, a prefix sum, a hash map of seen values, or two pointers.
Review these before coding to avoid predictable interview regressions.
Wrong move: Loop endpoints miss first/last candidate.
Usually fails on: Fails on minimal arrays and exact-boundary answers.
Fix: Re-derive loops from inclusive/exclusive ranges before coding.
Wrong move: Zero-count keys stay in map and break distinct/count constraints.
Usually fails on: Window/map size checks are consistently off by one.
Fix: Delete keys when count reaches zero.