Trains the technique from
LeetCode 261Graph Valid TreeThis 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.
Example 1
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
Five links for five cabinets is one too many, and indeed cabinets 1, 2 and 3 sit in a closed loop.
Example 3
Two links leave two separate pairs of cabinets, so nothing in one pair reaches anything in the other.
The editor is preloaded with this. It matches the parent problem's shape, so a solution that works here transfers to a judge unchanged.
def valid_tree(n: int, links: list[list[int]]) -> bool:public boolean validTree(int n, int[][] links)See the step-by-step animation, the intuition, and clean code in every language — free, no credit card.