793. Complete Components

A regional rail network joins n stations, numbered 0 to n - 1. Each entry [a, b] of edges is a direct two-way line between stations a and b. A group of stations that can reach one another through lines is a zone.

A zone is fully meshed when every pair of stations inside it has its own direct line. A zone made of one station counts as fully meshed, because it has no pair to connect. Return how many zones are fully meshed. No pair of stations is listed twice and no line joins a station to itself.

Example 1

Input:
n = 7, edges = [[0,1],[1,2],[0,2],[3,4],[4,5]]
Output:
2
Explanation:

The group {0,1,2} is a full triangle and the lone node 6 trivially qualifies; {3,4,5} lacks the link 3-5. That gives 2.

Example 2

Input:
n = 6, edges = [[0,3],[2,5],[1,4]]
Output:
3
Explanation:

The stations pair up as 0-3, 2-5 and 1-4; each pair is joined by its line, so all three zones are fully meshed and the answer is 3.

Example 3

Input:
n = 5, edges = [[0,1],[1,2],[2,3],[3,4]]
Output:
0
Explanation:

The only component is a path of five nodes, which is missing most of its links, so the answer is 0.

Constraints

  • 1 ≤ n ≤ 2 * 105
  • 0 ≤ edges.length ≤ 2 * 105
  • 0 ≤ a, b < n and a ≠ b
  • No duplicate lines (a pair appears at most once in either order).

How this problem is judged

Answers
Your answer must match exactly. Numbers compare by value, so 2 and 2.0 are equal.
Time per case
Python 200 msC++ 50 msJava 100 msJavaScript 100 msTypeScript 100 ms

Expected complexity

Time
O((n + m) * alpha(n))
Space
O(n)

What the author was aiming for. Your own solution is not measured against it.

Asked in an interview

Were you asked this in an interview? Say where, anonymously.

Code
Loading the editor…