All problems
1014MediumDepth-First SearchBreadth-First SearchUnion-FindGraph Theory

Does the Cabling Form a Single Tree

Tracked in this browser only
Write code

Trains the technique from

LeetCode 261Graph Valid Tree

This is an original problem, written from a brief that listed the technique, the difficulty, the topics, the function shape and the input bounds — none of that problem's wording, examples, hints or editorials. The link is there so you can map your practice onto the standard set.

Same function shape, different story and different numbers.

A site has n cabinets numbered 0 through n - 1, joined by the two-way links links, where links[i] = [a, b] joins cabinet a and cabinet b.

Return whether the links form a single tree: every cabinet reachable from every other, and no closed loop of links anywhere.

Examples

Example 1

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

Four links join five cabinets, cabinet 0 reaches 1, 2 and 3 directly and 4 through 1, and no link ever joins two cabinets already connected.

Example 2

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

Five links for five cabinets is one too many, and indeed cabinets 1, 2 and 3 sit in a closed loop.

Example 3

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

Two links leave two separate pairs of cabinets, so nothing in one pair reaches anything in the other.

Constraints

  • 1 <= n <= 2000
  • 0 <= links.length <= 5000
  • links[i].length == 2
  • 0 <= links[i][j] <= n - 1
  • The two ends of a link are different cabinets.
  • No pair of cabinets is linked twice.

The signature

The editor is preloaded with this. It matches the parent problem's shape, so a solution that works here transfers to a judge unchanged.

Python
def valid_tree(n: int, links: list[list[int]]) -> bool:
Java
public boolean validTree(int n, int[][] links)
September 7
Apply