#3558

Number of Ways to Assign Edge Weights I

Medium
MathTreeDepth-First SearchDepth-First SearchDynamic Programming
LeetCode ↗

Approaches

Brute ForceOptimal
Complexity Comparison
Brute ForceOptimal Solution
Time
O(n²)
O(n)
Space
O(1)
O(n)
💡

Intuition

Time O(n)Space O(n)

Use DFS to find the maximum depth and count the edges in the path. The total weight can be odd if the number of edges with weight 1 is odd.

⚙️

Algorithm

3 steps
  1. 1Step 1: Perform DFS to find the maximum depth and count edges in the path to that depth.
  2. 2Step 2: Calculate the number of ways to assign weights such that the total weight is odd.
  3. 3Step 3: Return the result modulo 10^9 + 7.
solution.py18 lines
1def count_odd_assignments(edges):
2    from collections import defaultdict
3    graph = defaultdict(list)
4    for u, v in edges:
5        graph[u].append(v)
6        graph[v].append(u)
7    max_depth = 0
8    def dfs(node, parent, depth):
9        nonlocal max_depth
10        max_depth = max(max_depth, depth)
11        for neighbor in graph[node]:
12            if neighbor != parent:
13                dfs(neighbor, node, depth + 1)
14    dfs(1, -1, 0)
15    return pow(2, max_depth - 1, 10**9 + 7) if max_depth > 0 else 0
16
17# Example usage
18print(count_odd_assignments([[1, 2]]))

Complexity note: DFS traverses each node once, leading to linear complexity relative to the number of nodes.

  • 1The path to the deepest node determines the edge count.
  • 2Odd total weights require careful assignment of weights.

Solutions and explanations are original Tejav content. Problem titles © LeetCode — use the LeetCode button above for the full problem statement.