Skip to content

Reachable Pair Check

Easy#union-find#connectivity~15 min

The mission

Problem

A network has n nodes numbered 0 to n minus 1 and a list of two-way links between pairs of nodes. Given a source node and a target node, decide whether some chain of links leads from one to the other. A node always reaches itself.

Examples

Input:  n = 3, links = [[0, 1], [1, 2], [2, 0]], source = 0, target = 2
Output: True
Input:  n = 6, links = [[0, 1], [0, 2], [3, 5], [5, 4], [4, 3]], source = 0, target = 5
Output: False
Why:    the links form two separate groups, {0, 1, 2} and {3, 4, 5}
Input:  n = 1, links = [], source = 0, target = 0
Output: True
Why:    edge case, a node reaches itself without any link

Hints

0 / 3

Target time
O((n + m) · α(n))
Target space
O(n)

Constraints

  • nodes are numbered 0 to n − 1

Stuck on the idea rather than the code? Disjoint Sets Basics covers it.

Python 3Ctrl+Enter runs
Custom test case