Number of Ways to Assign Edge Weights II - Problem

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

Initially, all edges have weight 0. Your task is to assign each edge a weight of either 1 or 2. The cost of a path between any two nodes is the sum of all edge weights along that path.

Given a 2D array queries where queries[i] = [u_i, v_i], for each query you need to determine: How many ways can you assign weights (1 or 2) to edges in the path between nodes u_i and v_i such that the total path cost is odd?

Important: For each query, only consider edges that are part of the path between the two query nodes. Return results modulo 10^9 + 7.

Input & Output

example_1.py โ€” Basic Tree
$ Input: n = 4, edges = [[1,2],[2,3],[3,4]], queries = [[1,3],[2,4]]
โ€บ Output: [2, 2]
๐Ÿ’ก Note: For query [1,3]: path is 1-2-3 (2 edges). We can assign weights (1,1), (1,2), (2,1), (2,2) giving sums 2,3,3,4. Exactly 2 are odd. For query [2,4]: path is 2-3-4 (2 edges), same logic gives 2 odd sums.
example_2.py โ€” Single Edge
$ Input: n = 2, edges = [[1,2]], queries = [[1,2]]
โ€บ Output: [1]
๐Ÿ’ก Note: Path 1-2 has 1 edge. Possible weights: (1) sum=1 odd, (2) sum=2 even. So 2^(1-1) = 1 way gives odd sum.
example_3.py โ€” Same Node Query
$ Input: n = 3, edges = [[1,2],[2,3]], queries = [[1,1]]
โ€บ Output: [0]
๐Ÿ’ก Note: Query asks for path from node 1 to itself. No edges in path, so no way to get an odd sum. Answer is 0.

Constraints

  • 2 โ‰ค n โ‰ค 104
  • edges.length = n - 1
  • 1 โ‰ค ui, vi โ‰ค n
  • 1 โ‰ค queries.length โ‰ค 104
  • The given edges form a valid tree

Visualization

Tap to expand
1234Road ARoad BRoad CQuery: Path from City 1 to City 3Path: 1 โ†’ 2 โ†’ 3 (uses roads A and B)Roads in path: 2Mathematical result: 2^(2-1) = 2 ways for odd sumโœ“ No need to check all 4 combinations!
Understanding the Visualization
1
Build Road Network
Create adjacency list representation of the tree from given edges
2
Find Route
For each query, find the unique path between source and destination nodes
3
Apply Mathematical Formula
Use the insight that exactly 2^(k-1) configurations give odd sums for k road segments
Key Takeaway
๐ŸŽฏ Key Insight: The mathematical approach recognizes that exactly half of all weight combinations produce odd sums, making direct calculation possible without enumeration.
Asked in
Google 15 Amazon 12 Meta 8 Microsoft 6
26.1K Views
Medium Frequency
~25 min Avg. Time
847 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