Program to count number of unique paths that includes given edges in Python

Given a list of edges representing a tree, we need to find the total number of unique paths that include each edge. A path in a tree connects any two nodes, and we count how many such paths pass through each given edge.

Problem Understanding

For the input edges = [[0, 1], [0, 2], [1, 3], [1, 4]], we have a tree structure where removing an edge splits the tree into two subtrees. The number of unique paths through an edge equals the product of nodes in each subtree.

0 1 2 3 4

Algorithm Steps

The solution uses depth-first search (DFS) to count subtree sizes ?

  • Build an adjacency list from the edges
  • Use DFS to count nodes in each subtree
  • For each edge, calculate paths as subtree_size × (total_nodes - subtree_size)

Implementation

from collections import defaultdict

class Solution:
    def solve(self, edges):
        adj = defaultdict(list)
        for a, b in edges:
            adj[a].append(b)
            adj[b].append(a)
        
        count = defaultdict(int)
        
        def dfs(x, parent):
            count[x] = 1
            for nb in adj[x]:
                if nb == parent:
                    continue
                count[x] += dfs(nb, x)
            return count[x]
        
        dfs(0, -1)
        ans = []
        for a, b in edges:
            x = min(count[a], count[b])
            ans.append(x * (count[0] - x))
        return ans

# Test the solution
ob = Solution()
edges = [
    [0, 1],
    [0, 2],
    [1, 3],
    [1, 4]
]
print(ob.solve(edges))
[6, 4, 4, 4]

How It Works

The DFS function counts the number of nodes in each subtree. For edge (a, b), we take the minimum count which represents the smaller subtree. The formula x * (total_nodes - x) gives us all possible paths crossing that edge ?

Example Breakdown

For edge [0, 1] ? Subtree sizes are 3 (nodes 1,3,4) and 2 (nodes 0,2). Paths = 3 × 2 = 6.

Key Points

  • Each edge splits the tree into two components
  • Paths through an edge = size_of_subtree1 × size_of_subtree2
  • DFS calculates subtree sizes efficiently in O(n) time
  • Total complexity is O(n) where n is the number of nodes

Conclusion

This algorithm efficiently counts unique paths through each edge using DFS to determine subtree sizes. The key insight is that paths through an edge equal the product of nodes on each side of that edge.

Updated on: 2026-03-25T13:49:39+05:30

419 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements