← Questions
Group movies by graph traversal
0
I was asked this
No reports yet. Sign in to say where you were asked it.
A coding interview question asked in Google's onsite coding round, last asked Sep 2025. It tests graphs, bfs and dfs.
Movies are labelled 0 to n - 1, and a list of undirected pairs (a, b) says that movies a and b are similar. Similarity carries through links, so a category is a maximal set of movies connected by similarity pairs (a connected component). Return every category. Implement it with BFS and with DFS, then discuss union-find.
Interface
Unless you agree on a different interface with the interviewer, assume:
-
group_movies(n: int, pairs: list[tuple[int, int]]) -> list[list[int]]— each category sorted ascending, and the categories ordered by their smallest id. A movie with no pairs is a category on its own.
Example
group_movies(8, [(0, 1), (1, 2), (3, 4), (5, 6), (6, 7)])
-> [[0, 1, 2], [3, 4], [5, 6, 7]]
group_movies(4, [(2, 0)])
-> [[0, 2], [1], [3]]
Constraints
- Up to 10^5 movies and 2 · 10^5 pairs; pairs may repeat or link a movie to itself.
Clarifying questions
- Are pairs undirected?
- Should movies without any pair appear as single-movie categories?
- Is the output order fixed, or is any order fine?
- Do pairs arrive all at once, or over time?
What a strong answer covers
- An adjacency list, then a BFS or DFS from every unvisited movie, marking movies visited when they are pushed. O(n + E) time and space.
- Iterative DFS with an explicit stack versus recursive DFS, and why recursion can overflow on a long chain of 10^5 movies.
- Sorting inside each category and ordering the categories; starting the scan from movie 0 upward gives the order for free.
- Union-find with path compression and union by rank: no adjacency list needed, near-linear time, and the right choice when pairs arrive over time.
- Dry-running the first example.
Follow-ups
- Pairs arrive as a stream; answer "are movies
aandbin the same category?" at any time. - Pairs can be removed.
- Similarity has a strength; only links above a threshold count, and the threshold changes per query.
Where it's asked
- Google · Onsite coding · Last asked Sep 202545 min · Usually two rounds, mostly in person: whiteboard plus a Chromebook with Google Docs · No AI (a pilot code-comprehension round lets candidates use Gemini)
What it tests
No official answer yet. Write yours on the right and run it.
Nothing published yet.
Sign in to submit your code; every attempt is kept here.
Write and test your solution herePython in your browser, the question's tests level by level, every submission kept for you.Sign in to start coding
