Count Pairs of Offices That Cannot Reach Each Other
Last updated: November 29, 2026
Quick Overview
Given n Google offices and a list of undirected network links, return the number of unordered pairs of offices that have no path between them.
0
0
0 solved
Given n Google offices and a list of undirected network links, return the number of unordered pairs of offices that have no path between them.
A union-find plus counting question that appears in online assessments. Interviewers want component sizes from union-find and then the pair count without the O(n^2) double loop, and they check that you use integers large enough for the answer.
What the Interviewer Expects
- Groups offices into components with union-find
- Collects each component size at its root
- Counts cross-component pairs with a running prefix sum
- Avoids enumerating pairs explicitly
- Notes the answer can be about n^2 / 2 in size
Key Topics to Cover
How to Approach This
- Clarify input constraints and edge cases before writing code.
- Walk through your approach verbally and confirm with the interviewer before coding.
- Start with a brute force solution, then optimize. Mention time and space complexity.
- Test your solution with examples, including edge cases like empty input or duplicates.
- Consider common patterns: sliding window, two pointers, hash map, BFS/DFS, dynamic programming.
Possible Follow-up Questions
- Return the count after each new link instead of only at the end.
- Count pairs that are reachable but more than k hops apart; can union-find help?
- What if links are directed?
Sharpen Your Skills on Codemia
Practice similar problems with our interactive workspace, get AI feedback, and track your progress.
Practice DSA ProblemsSample Answer
Requirements
- Input:
nand a list of[a, b]links. - Output: number of pairs
(u, v)withu < vand no path between them. - Offices with no links are isolated components of size 1....
High-Level Design
After union-find, each office belongs to a component with known size. Two offices are unreachable exactly when they sit in different components. Process components in any order, keeping seen, the to...