← Questions
Fewest new paths to connect every island
0
I was asked this
No reports yet. Sign in to say where you were asked it.
A coding interview question asked in Meta's technical phone screen, last asked Jul 2025. It tests union-find and graphs.
You have n islands and a list of existing two-way paths between pairs of them. You may build a new path between any two islands. Return the fewest new paths needed so that every island can reach every other.
Interface
Unless you agree on a different interface with the interviewer, assume:
-
min_new_paths(islands: list[str], paths: list[tuple[str, str]]) -> int— island names are distinct; each path joins two different islands. Duplicate paths may appear.
Example
min_new_paths(["a", "b", "c", "d", "e"], [("a", "b"), ("b", "c"), ("d", "e")]) -> 1 # {a,b,c} and {d,e}
min_new_paths(["a", "b", "c", "d"], []) -> 3
min_new_paths(["a", "b"], [("a", "b"), ("b", "a")]) -> 0 # duplicates change nothing
Constraints
-
1 <= n <= 200,000;0 <= len(paths) <= 200,000. - Paths are undirected.
Clarifying questions
- Are paths two-way?
- Can the same path appear twice, or a path from an island to itself?
- Can a path mention an island that is not in the list?
- Do you want just the count, or which new paths to build?
What a strong answer covers
- The key fact: the answer is the number of connected components minus one, because each new path can merge at most two components.
- Counting components with union-find (path compression and union by size or rank, near-linear time) or with BFS or DFS over an adjacency list.
- Mapping string names to integer ids first.
- Tests: no paths, already connected, duplicate paths, a single island.
Follow-ups
- Return one concrete set of new paths (link one island from each component to the next).
- Each possible new path has a cost: what is the cheapest way to connect everything (a minimum spanning tree)?
- Paths are added over time; report the answer after each addition.
Where it's asked
- Meta · Technical phone screen · Last asked Jul 202545 min · Two coding problems in CoderPad, about 20 minutes each · Usually no AI; some newer screens are AI-assisted
What it tests
union-find · graphs
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
