Max GCD of Siblings in a Binary Tree Given as List of Edges
Last Updated : 2 Jun, 2026
Given a 2D list that represents the nodes of a Binary tree with n nodes, find the maximum GCD of the siblings of this tree without actually constructing it. If there are no pairs of siblings in the given tree, print 0. Also, if given that there's an edge between a and b in the form of [a,b] in the list, then a is the parent node.
[Naive Approach] Using Nested Traversal - O(E^2 * log(V)) Time O(1) Space
The idea is to compare every pair of edges and check whether both edges have the same parent node. If two edges have the same parent, then their child nodes are siblings. Compute the GCD of such sibling pairs and maintain the maximum GCD obtained among all pairs.
Output
6
Time Complexity: O(E^2 * log(V)) Auxiliary Space: O(1)
[Expected Approach] Using Sorting and Adjacent Comparison - O(E * log(E)) Time O(1) Space
The idea is to sort the edges based on the parent node. After sorting, children belonging to the same parent become adjacent in the array. Traverse the sorted edges and whenever two consecutive edges have the same parent, they form a sibling pair. Compute the GCD of those sibling nodes and update the maximum GCD obtained.
Let us understand with example: Input: arr = [[4, 5], [4, 2], [2, 3], [2, 1], [3, 6], [3, 12]] After sorting: [[2, 1], [2, 3], [3, 6], [3, 12], [4, 2], [4, 5]]
Compare [2, 1] and [2, 3] -> Same parent 2, GCD(1, 3) = 1, so res = 1.
Compare [3, 6] and [3, 12] -> Same parent 3, GCD(6, 12) = 6, so res = 6.
Compare [4, 2] and [4, 5] -> Same parent 4, GCD(2, 5) = 1, so res remains 6.
Final Output: 6
Output
6
Time Complexity: O(E * log(E)) Auxiliary Space: O(1)