Number of Ways to Assign Edge Weights I - Problem

You're given an undirected tree with n nodes labeled from 1 to n, rooted at node 1. The tree is represented by a 2D array edges where edges[i] = [u_i, v_i] indicates an edge between nodes u_i and v_i.

Your task: Assign each edge a weight of either 1 or 2. Find a node x at the maximum depth from the root, then count how many ways you can assign weights to the edges on the path from node 1 to node x such that the total path cost is odd.

Key points:

  • Initially all edges have weight 0
  • You must assign weight 1 or 2 to each edge
  • Consider only edges in the path from root (1) to the deepest node
  • Return the count modulo 10^9 + 7

Input & Output

example_1.py โ€” Basic Tree
$ Input: n = 4, edges = [[1,2],[1,3],[2,4]]
โ€บ Output: 2
๐Ÿ’ก Note: Tree structure: 1-2-4 and 1-3. Deepest node is 4. Path 1โ†’2โ†’4 has 2 edges. We can assign weights (1,1), (1,2), (2,1), or (2,2). Sums are 2, 3, 3, 4. Exactly 2 assignments (1,2) and (2,1) give odd sum 3.
example_2.py โ€” Linear Tree
$ Input: n = 3, edges = [[1,2],[2,3]]
โ€บ Output: 2
๐Ÿ’ก Note: Linear tree: 1-2-3. Deepest node is 3. Path 1โ†’2โ†’3 has 2 edges. Same analysis as example 1: 2^(2-1) = 2 ways give odd sums.
example_3.py โ€” Single Node
$ Input: n = 1, edges = []
โ€บ Output: 0
๐Ÿ’ก Note: Only one node, no edges. Path length is 0, so no way to get an odd sum.

Constraints

  • 1 โ‰ค n โ‰ค 105
  • edges.length = n - 1
  • The input represents a valid tree
  • 1 โ‰ค ui, vi โ‰ค n
  • ui โ‰  vi

Visualization

Tap to expand
Edge Weight Assignment Problem12341 or 21 or 2Solution Steps1. Find deepest node (4)2. Path: 1โ†’2โ†’4 (k=2 edges)3. Apply formula: 2^(k-1)4. Answer: 2^(2-1) = 2Odd combinations:(1,2)โ†’3, (2,1)โ†’3
Understanding the Visualization
1
Build the Tree
Create graph from edges and root at node 1
2
Find Deepest Path
Use DFS to find the node at maximum depth
3
Count Edge Assignments
Apply formula: 2^(path_length - 1) for odd sums
Key Takeaway
๐ŸŽฏ Key Insight: For k edges in the path to the deepest node, exactly 2^(k-1) weight assignments produce odd total costs, giving us an O(n) mathematical solution.
Asked in
Google 15 Meta 12 Amazon 8 Microsoft 6
23.4K Views
Medium Frequency
~15 min Avg. Time
890 Likes
Ln 1, Col 1
Smart Actions
๐Ÿ’ก Explanation
AI Ready
๐Ÿ’ก Suggestion Tab to accept Esc to dismiss
// Output will appear here after running code
Code Editor Closed
Click the red button to reopen