Number of Ways to Assign Edge Weights I - Problem

There is an undirected tree with n nodes labeled from 1 to n, rooted at node 1. The tree is represented by a 2D integer array edges of length n - 1, where edges[i] = [ui, vi] indicates that there is an edge between nodes ui and vi.

Initially, all edges have a weight of 0. You must assign each edge a weight of either 1 or 2.

The cost of a path between any two nodes u and v is the total weight of all edges in the path connecting them.

Select any one node x at the maximum depth. Return the number of ways to assign edge weights in the path from node 1 to x such that its total cost is odd.

Since the answer may be large, return it modulo 109 + 7.

Note: Ignore all edges not in the path from node 1 to x.

Input & Output

Example 1 — Linear Path Tree
$ Input: n = 4, edges = [[1,2],[2,3],[3,4]]
Output: 4
💡 Note: Tree is 1→2→3→4. Maximum depth is 3. Path 1→4 has 3 edges. We need odd total weight. Possible assignments: [1,2,2]=5, [2,1,2]=5, [2,2,1]=5, [1,1,1]=3. Total: 4 ways.
Example 2 — Single Edge Tree
$ Input: n = 2, edges = [[1,2]]
Output: 1
💡 Note: Tree is 1→2. Maximum depth is 1. Path has 1 edge. For odd sum, assign weight 1. Only 1 way: [1]=1.
Example 3 — Branched Tree
$ Input: n = 5, edges = [[1,2],[1,3],[2,4],[2,5]]
Output: 2
💡 Note: Tree has nodes 4 and 5 at max depth 2. Path 1→2→4 has 2 edges. For odd sum: [1,2]=3 or [2,1]=3. Total: 2 ways.

Constraints

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

Visualization

Tap to expand
Number of Ways to Assign Edge Weights I INPUT 1 2 3 4 w1 w2 w3 depth 0 depth 1 depth 2 depth 3 n = 4 edges = [[1,2],[2,3],[3,4]] ALGORITHM STEPS 1 Find Max Depth Node Node 4 at depth 3 2 Count Path Edges Path 1-->2-->3-->4: k=3 edges 3 Odd Cost Condition Need odd number of weight-1 edges 4 Calculate Ways Ways = 2^(k-1) = 2^2 = 4 Valid Combinations: (1,1,1): 1+1+1=3 [OK] (1,2,2): 1+2+2=5 [OK] (2,1,2): 2+1+2=5 [OK] (2,2,1): 2+2+1=5 [OK] FINAL RESULT Path from root to max depth: 1 1|2 2 1|2 3 1|2 4 OUTPUT 4 Key Insight: For a path with k edges, we need an odd sum. Each edge can be 1 or 2. The sum is odd when there's an odd count of 1s. This equals half of all 2^k combinations = 2^(k-1). With k=3 edges: 2^(3-1) = 2^2 = 4 ways. Answer modulo 10^9+7. TutorialsPoint - Number of Ways to Assign Edge Weights I | Optimal Solution
Asked in
Google 35 Amazon 28
29.5K Views
Medium Frequency
~25 min Avg. Time
892 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