1259. Silent Tree Paths
A cable network is a tree of n junctions numbered 0 to n - 1. Each entry edges[i] = [u, v, w] is a cable joining junctions u and v and carrying the signal mask w. The value of a path is the XOR of the masks of the cables along it. There are exactly n - 1 cables and they connect all junctions.
Given n, edges and an integer k, return the number of unordered pairs of different junctions u < v whose connecting path has value exactly k, as a long. The tree may be a very long chain, so use an iterative traversal. Aim for O(n) expected time and O(n) space: compute the XOR from junction 0 to every junction, since the path value between two junctions is the XOR of their two root values, then count pairs with a hash map.
Example 1
- Input:
- n = 4, edges = [[0,1,5],[1,2,3],[1,3,6]], k = 6
- Output:
- 2
- Explanation:
Path values: 0-1 is 5, 1-2 is 3, 1-3 is 6, 0-2 is 5^3 = 6, 0-3 is 5^6 = 3, 2-3 is 3^6 = 5; the pairs (1,3) and (0,2) equal 6, so the answer is 2.
Example 2
- Input:
- n = 3, edges = [[0,1,2],[1,2,2]], k = 0
- Output:
- 1
- Explanation:
Only the path from junction 0 to junction 2 has value 2 ^ 2 = 0, so one pair matches k = 0.
Example 3
- Input:
- n = 1, edges = [], k = 0
- Output:
- 0
- Explanation:
A single junction has no pair of different junctions, so the answer is 0.
Constraints
1 ≤ n ≤ 105; edges.length == n - 1 and the edges form a tree; 0 ≤ u, v < n; 0 ≤ w, k < 230.
How this problem is judged
- Answers
- Your answer must match exactly. Numbers compare by value, so 2 and 2.0 are equal.
- Time per case
- Python 4,000 msC++ 1,000 msJava 2,000 msJavaScript 2,000 msTypeScript 2,000 ms
Expected complexity
- Time
- O(n)
- Space
- O(n)