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.

Example:  

Input: arr = [[4, 5], [4, 2], [2, 3], [2, 1], [3, 6], [3, 12]] 
Output: 6
Explanation:

blobid0_1779965479

For the above tree, the maximum GCD for the siblings is 6, formed for the nodes 6 and 12 for the children of node 3.

Input: arr[] = [[1, 2], [1, 4]] 
Output : 2
Explanation:

blobid1_1779965502

For the above tree, the maximum GCD for the siblings is 2, formed for the nodes 2 and 4 for the children of node 1.

Try It Yourself
redirect icon

[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.

C++
#include <iostream>
using namespace std;

int maxBinTreeGCD(vector<vector<int>> &arr)
{

    int n = arr.size();
    int res = 0;

    // Compare every pair of edges
    for (int i = 0; i < n; i++)
    {
        for (int j = i + 1; j < n; j++)
        {

            // Same parent means siblings
            if (arr[i][0] == arr[j][0])
            {

                res = max(res, __gcd(arr[i][1], arr[j][1]));
            }
        }
    }

    return res;
}

// Driver Code
int main()
{

    vector<vector<int>> arr = {{4, 5}, {4, 2}, {2, 3}, {2, 1}, {3, 6}, {3, 12}};

    cout << maxBinTreeGCD(arr);

    return 0;
}
Java
import java.util.ArrayList;
import java.util.List;

public class GfG {

    static int gcd(int a, int b)
    {
        if (b == 0) {
            return a;
        }
        return gcd(b, a % b);
    }

    static int maxBinTreeGCD(List<List<Integer> > arr)
    {

        int n = arr.size();
        int res = 0;

        // Compare every pair of edges
        for (int i = 0; i < n; i++) {
            for (int j = i + 1; j < n; j++) {

                // Same parent means siblings
                if (arr.get(i).get(0)
                    == arr.get(j).get(0)) {

                    res = Math.max(res,
                                   gcd(arr.get(i).get(1),
                                       arr.get(j).get(1)));
                }
            }
        }

        return res;
    }

    public static void main(String[] args)
    {

        List<List<Integer> > arr = new ArrayList<>();
        arr.add(new ArrayList<>(List.of(4, 5)));
        arr.add(new ArrayList<>(List.of(4, 2)));
        arr.add(new ArrayList<>(List.of(2, 3)));
        arr.add(new ArrayList<>(List.of(2, 1)));
        arr.add(new ArrayList<>(List.of(3, 6)));
        arr.add(new ArrayList<>(List.of(3, 12)));

        System.out.println(maxBinTreeGCD(arr));
    }
}
Python
from math import gcd
from typing import List


def maxBinTreeGCD(arr: List[List[int]]) -> int:

    n = len(arr)
    res = 0

    # Compare every pair of edges
    for i in range(n):
        for j in range(i + 1, n):

            # Same parent means siblings
            if arr[i][0] == arr[j][0]:

                res = max(res, gcd(arr[i][1], arr[j][1]))

    return res


# Driver Code
if __name__ == "__main__":
    arr = [[4, 5], [4, 2], [2, 3], [2, 1], [3, 6], [3, 12]]

    print(maxBinTreeGCD(arr))
C#
using System;
using System.Collections.Generic;

public class GfG {
    public int GCD(int a, int b)
    {
        if (b == 0)
            return a;
        return GCD(b, a % b);
    }

    public int maxBinTreeGCD(List<List<int> > arr)
    {
        int n = arr.Count;
        int res = 0;

        // Compare every pair of edges
        for (int i = 0; i < n; i++) {
            for (int j = i + 1; j < n; j++) {
                // Same parent means siblings
                if (arr[i][0] == arr[j][0]) {
                    res = Math.Max(
                        res, GCD(arr[i][1], arr[j][1]));
                }
            }
        }

        return res;
    }

    public static void Main()
    {
        List<List<int> > arr = new List<List<int> >{
            new List<int>{ 4, 5 }, new List<int>{ 4, 2 },
            new List<int>{ 2, 3 }, new List<int>{ 2, 1 },
            new List<int>{ 3, 6 }, new List<int>{ 3, 12 }
        };

        GfG obj = new GfG();
        Console.WriteLine(obj.maxBinTreeGCD(arr));
    }
}
JavaScript
function gcd(a, b) {
    if (b === 0) {
        return a;
    }
    return gcd(b, a % b);
}

function maxBinTreeGCD(arr) {

    let n = arr.length;
    let res = 0;

    // Compare every pair of edges
    for (let i = 0; i < n; i++) {
        for (let j = i + 1; j < n; j++) {

            // Same parent means siblings
            if (arr[i][0] === arr[j][0]) {

                res = Math.max(res, gcd(arr[i][1], arr[j][1]));
            }
        }
    }

    return res;
}

// Driver Code
let arr = [[4, 5], [4, 2], [2, 3], [2, 1], [3, 6], [3, 12]];

console.log(maxBinTreeGCD(arr));

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

C++
#include <iostream>
using namespace std;

int maxBinTreeGCD(vector<vector<int>> &arr)
{

    // Need at least 2 edges to form siblings
    if (arr.size() < 2)
        return 0;

    // Sort by parent node
    sort(arr.begin(), arr.end());

    int res = 0;

    // Compare adjacent edges
    for (int i = 1; i < arr.size(); i++)
    {

        // Same parent => siblings
        if (arr[i][0] == arr[i - 1][0])
        {

            res = max(res, __gcd(arr[i][1], arr[i - 1][1]));
        }
    }

    return res;
}

// Driver Code
int main()
{

    vector<vector<int>> arr = {{4, 5}, {4, 2}, {2, 3}, {2, 1}, {3, 6}, {3, 12}};

    cout << maxBinTreeGCD(arr);

    return 0;
}
Java
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.List;

public class GfG {
    public static int gcd(int a, int b)
    {
        if (b == 0) {
            return a;
        }
        return gcd(b, a % b);
    }

    public static int
    maxBinTreeGCD(List<List<Integer> > arr)
    {
        // Need at least 2 edges to form siblings
        if (arr.size() < 2)
            return 0;

        // Sort by parent node
        Collections.sort(
            arr, (a, b) -> a.get(0).compareTo(b.get(0)));

        int res = 0;

        // Compare adjacent edges
        for (int i = 1; i < arr.size(); i++) {

            // Same parent => siblings
            if (arr.get(i).get(0).equals(
                    arr.get(i - 1).get(0))) {
                res = Math.max(res,
                               gcd(arr.get(i).get(1),
                                   arr.get(i - 1).get(1)));
            }
        }

        return res;
    }

    public static void main(String[] args)
    {
        List<List<Integer> > arr = new ArrayList<>();
        arr.add(Arrays.asList(4, 5));
        arr.add(Arrays.asList(4, 2));
        arr.add(Arrays.asList(2, 3));
        arr.add(Arrays.asList(2, 1));
        arr.add(Arrays.asList(3, 6));
        arr.add(Arrays.asList(3, 12));

        System.out.println(maxBinTreeGCD(arr));
    }
}
Python
from math import gcd


def maxBinTreeGCD(arr):

    # Need at least 2 edges to form siblings
    if len(arr) < 2:
        return 0

    # Sort by parent node
    arr.sort(key=lambda x: x[0])

    res = 0

    # Compare adjacent edges
    for i in range(1, len(arr)):

        # Same parent => siblings
        if arr[i][0] == arr[i - 1][0]:
            res = max(res, gcd(arr[i][1], arr[i - 1][1]))

    return res


# Driver Code
if __name__ == "__main__":
    arr = [[4, 5], [4, 2], [2, 3], [2, 1], [3, 6], [3, 12]]

    print(maxBinTreeGCD(arr))
C#
using System;
using System.Collections.Generic;

class GfG {
    static int GCD(int a, int b)
    {
        if (b == 0)
            return a;

        return GCD(b, a % b);
    }

    static int maxBinTreeGCD(List<List<int> > arr)
    {
        // Need at least 2 edges to form siblings
        if (arr.Count < 2)
            return 0;

        // Sort by parent node
        arr.Sort(delegate(List<int> a, List<int> b) {
            if (a[0] != b[0])
                return a[0].CompareTo(b[0]);

            return a[1].CompareTo(b[1]);
        });

        int res = 0;

        // Compare adjacent edges
        for (int i = 1; i < arr.Count; i++) {
            // Same parent => siblings
            if (arr[i][0] == arr[i - 1][0]) {
                res = Math.Max(
                    res, GCD(arr[i][1], arr[i - 1][1]));
            }
        }

        return res;
    }

    static int Main()
    {
        List<List<int> > arr = new List<List<int> >{
            new List<int>{ 4, 5 }, new List<int>{ 4, 2 },
            new List<int>{ 2, 3 }, new List<int>{ 2, 1 },
            new List<int>{ 3, 6 }, new List<int>{ 3, 12 }
        };

        Console.WriteLine(maxBinTreeGCD(arr));

        return 0;
    }
}
JavaScript
function gcd(a, b) {
    if (b === 0) {
        return a;
    }
    return gcd(b, a % b);
}

function maxBinTreeGCD(arr) {
    // Need at least 2 edges to form siblings
    if (arr.length < 2) {
        return 0;
    }

    // Sort by parent node
    arr.sort((a, b) => a[0] - b[0]);

    let res = 0;

    // Compare adjacent edges
    for (let i = 1; i < arr.length; i++) {
        // Same parent => siblings
        if (arr[i][0] === arr[i - 1][0]) {
            res = Math.max(res, gcd(arr[i][1], arr[i - 1][1]));
        }
    }

    return res;
}

// Driver Code
const arr = [[4, 5], [4, 2], [2, 3], [2, 1], [3, 6], [3, 12]];

console.log(maxBinTreeGCD(arr));

Output
6

Time Complexity: O(E * log(E))
Auxiliary Space: O(1)

Comment