#2846
Minimum Edge Weight Equilibrium Queries in a Tree
HardArrayDynamic ProgrammingBit ManipulationTreeDepth-First SearchDFS for tree traversalFrequency counting with Hash Maps
Approaches
Brute ForceOptimal
Complexity Comparison
| Brute Force | Optimal Solution★ | |
|---|---|---|
| Time | O(n²) | O(n) |
| Space | O(1) | O(n) |
💡
Intuition
Time O(n)Space O(n)
By rooting the tree and using a frequency map to count edge weights along paths, we can efficiently determine the minimum changes needed for each query.
⚙️
Algorithm
3 steps- 1Step 1: Root the tree at an arbitrary node (e.g., node 0).
- 2Step 2: Create a frequency map (2D array) to store the count of each edge weight for paths from the root to each node.
- 3Step 3: For each query, use the precomputed frequency map to determine the maximum frequency of edge weights along the path and calculate the required changes.
solution.py22 lines
1def min_operations_optimal(n, edges, queries):
2 from collections import defaultdict
3 graph = defaultdict(list)
4 for u, v, w in edges:
5 graph[u].append((v, w))
6 graph[v].append((u, w))
7
8 freq = [defaultdict(int) for _ in range(n)]
9 def dfs(node, parent):
10 for neighbor, weight in graph[node]:
11 if neighbor != parent:
12 freq[neighbor][weight] += 1
13 for w, count in freq[node].items():
14 freq[neighbor][w] += count
15 dfs(neighbor, node)
16
17 dfs(0, -1)
18 results = []
19 for a, b in queries:
20 max_freq = max(freq[a].values(), default=0) + max(freq[b].values(), default=0)
21 results.append((len(freq[a]) + len(freq[b])) - max_freq)
22 return resultsℹ
Complexity note: This complexity is due to the single DFS traversal to build the frequency map, making it efficient for multiple queries.
- 1Understanding tree structure is crucial for efficient traversal and pathfinding.
- 2Using frequency maps allows for quick calculations of edge weights along paths.
Solutions and explanations are original Tejav content. Problem titles © LeetCode — use the LeetCode button above for the full problem statement.