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.

Google
Coding & Algorithms
Software Engineer
Google
November 29, 2026
Software Engineer
Online Assessment
Coding & Algorithms
Easy

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
Union-Find
Combinatorics
Connected Components
Prefix Sums
How to Approach This
  1. Clarify input constraints and edge cases before writing code.
  2. Walk through your approach verbally and confirm with the interviewer before coding.
  3. Start with a brute force solution, then optimize. Mention time and space complexity.
  4. Test your solution with examples, including edge cases like empty input or duplicates.
  5. 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 Problems
Sample Answer
Requirements
  • Input: n and a list of [a, b] links.
  • Output: number of pairs (u, v) with u < v and 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...


Submit Your Answer
Markdown supported