Check if given graph is tree or not

Pattern: Cycle detection

medium

An undirected graph on n vertices is a tree exactly when it has n - 1 edges and no cycle; with exactly n - 1 edges, having no cycle also makes it connected. Check the count, then union-find the edges.

The problem

Return whether the undirected graph is a tree: connected with no cycles. Vertices are numbered from 0 and each edge is given as [u, v].

Think first

  • How many edges does a tree on n vertices have?
  • With that many edges, what does 'no cycle' imply?
  • How do you detect a cycle?

Hints

    Brute force, and why it fails

    Check connectivity with DFS and cycles separately: also O(V + E).

    The key insight

    The edge count plus a cycle check together cover both conditions of being a tree.

    Dry run

    n = 4, edges 0-1, 1-2, 1-3: 3 = n - 1 edges.

    Step 1 of 3

    The plan

    if len(edges) != n - 1: false
    for (u, v): if find(u) == find(v): false; union
    true
    

    Complexity

    Time
    O(V + E α(V))
    Space
    O(V)

    One pass.

    Edge cases

    • One vertex, no edges: true.
    • Two pieces with the right count: impossible without a cycle.
    • Too many edges: false.
    I've built my logic, show the code

    Java

    class Solution {
        public boolean isTree(int n, int[][] edges) {
            if (edges.length != n - 1) return false;   // a tree on n vertices has exactly n - 1 edges
            int[] parent = new int[n];
            for (int i = 0; i < n; i++) parent[i] = i;
            for (int[] e : edges) {
                int a = find(parent, e[0]), b = find(parent, e[1]);
                if (a == b) return false;           // a cycle; with n - 1 edges that also means disconnected
                parent[a] = b;
            }
            return true;
        }
    
        private int find(int[] parent, int x) {
            while (parent[x] != x) x = parent[x] = parent[parent[x]];
            return x;
        }
    }

    C++

    class Solution {
    public:
        bool isTree(int n, vector<vector<int>>& edges) {
            if (static_cast<int>(edges.size()) != n - 1) return false;   // a tree on n vertices has exactly n - 1 edges
            vector<int> parent(n);
            for (int i = 0; i < n; i++) parent[i] = i;
            for (const vector<int>& e : edges) {
                int a = find(parent, e[0]), b = find(parent, e[1]);
                if (a == b) return false;           // a cycle; with n - 1 edges that also means disconnected
                parent[a] = b;
            }
            return true;
        }
    
        int find(vector<int>& parent, int x) {
            while (parent[x] != x) x = parent[x] = parent[parent[x]];
            return x;
        }
    };

    Python

    class Solution:
        def isTree(self, n: int, edges: list[list[int]]) -> bool:
            if len(edges) != n - 1:
                return False                        # a tree on n vertices has exactly n - 1 edges
            parent = list(range(n))
    
            def find(x):
                while parent[x] != x:
                    parent[x] = parent[parent[x]]
                    x = parent[x]
                return x
    
            for u, v in edges:
                a, b = find(u), find(v)
                if a == b:
                    return False                    # a cycle; with n - 1 edges that also means disconnected
                parent[a] = b
            return True

    Common mistakes

    • Only checking for cycles.
    • Only checking connectivity.

    Similar problems