Save 25%Black Friday: 25% off all plans — use code BLACKFRIDAY2026 at checkout. Ends Friday, Dec 4.Claim the deal

You are given a forest represented by relations, where each entry has the form [child, parent] and represents a direct parent relationship. The relationships form a valid acyclic forest, and each child has at most one direct parent.

Among the node IDs that appear in relations, a node that never appears as a child is the root of its tree. The size of a tree is the number of distinct nodes it contains, including its root.

Return the ID of the root of the tree with the greatest size. If multiple trees have the same maximum size, return the smallest root ID.

Constraints:

  • 1 ≤ relations.length ≤ 105
  • 1 ≤ relations[i][j] ≤ 109

Example 1:

Input: relations = [[2, 1], [3, 1], [4, 2], [5, 2], [6, 3], [7, 3], [9, 8]] Output: 1 Explanation: The tree rooted at 1 contains the nodes 1, 2, 3, 4, 5, 6, and 7. The separate tree rooted at 8 contains 8 and 9, so 1 is the root of the larger tree.

Tree rooted at 1:     Tree rooted at 8:
        1                     8
       / \                    |
      2   3                   9
     / \ / \
    4  5 6  7

Example 2:

Input: relations = [[30, 1], [31, 1], [40, 32], [41, 32], [42, 31], [43, 44]] Output: 1

Example 3:

Input: relations = [[15, 1], [16, 15], [17, 16], [18, 17], [10, 9], [8, 9], [7, 9]] Output: 1


Accepted
387/960
Acceptance Rate40.3%
Test Cases
Input
relations =
Output
Expected