Skip to the code
cf.
+50 XP

#476 Fewest Links So Every Page Reaches Every Page

hard

A docs team wants readers to be able to get from any page to any other page by following links. Pages are numbered 0 to n - 1, and links[i] = [a, b] means page a links to page b.

Write fewestNewLinks(n, links) that returns the smallest number of new links to add so that every page can reach every other page. If that is already true, return 0.

Example 1

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

Adding a link from page 2 back to page 0 closes the loop.

Example 2

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

Pages 0 and 2 have no links in and pages 1 and 3 have no links out. Two links, 1 → 2 and 3 → 0, fix all of them.

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).