Skip to the code
cf.
+25 XP

#475 Count Groups of Mutually Linked Pages

medium

A site-map tool groups pages that can all reach each other by following links. Pages are numbered 0 to n - 1, and links[i] = [a, b] means page a links to page b (one way).

Two pages are in the same group when each can reach the other by following links. Write countLinkedGroups(n, links) that returns the number of groups. A page that can't get back to itself through any other page is a group of one.

Example 1

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

Pages 0, 1, and 2 reach each other in a loop. Page 3 can't get back to 1, and 4 can't get back to 3, so they are groups of one.

Example 2

Input: n = 3, links = []
Output: 3

No links, so every page is alone.

Constraints

  • 1 <= n <= 10000
  • 0 <= links.length <= 50000
  • 0 <= a, b < n
Saved in this browser

Run tries your code on the examples. Submit runs every test, including hidden edge cases, and solves the problem when they all pass.

Ctrl + Enter runs, Ctrl + Shift + Enter submits (⌘ on a Mac).