Problem solution · Python

Minimum Edge Weight Equilibrium Queries in a Tree

Minimum Edge Weight Equilibrium Queries in a Tree: a Python solution using direct simulation. Learn the idea, check the complexity, and read the full code, with credit to walkccc LeetCode Solutions.

Technique
Direct simulation
Source
walkccc LeetCode Solutions
Length
85 lines
Start with the idea.

Try the problem first. If you get stuck, read the approach below, then write your own solution. The full code is at the bottom.

Approach

Direct simulation

For Minimum Edge Weight Equilibrium Queries in a Tree, the implementation follows the problem’s operations directly while maintaining only the state needed for the next decision.

  1. Translate each rule into one explicit state update.
  2. Maintain the invariant after every processed item.
  3. Return the accumulated state once all relevant input has been handled.

Code notes

  • 85 lines of Python from the credited upstream file 2846.py.
  • The implementation visibly relies on sequence storage.
  • No explicit loop blocks detected.

Complexity

Count the number and nesting of passes over the input, then include the maintained containers in the memory estimate.

Check the problem constraints before deciding whether this complexity will pass.

Source

Code and credit

This code comes from walkccc LeetCode Solutions by P.-Y. Chen (walkccc) and is used under the MIT licence.

Full codeMinimum Edge Weight Equilibrium Queries in a Tree · PythonPython
Use this to learn the idea, then write your own version.
class Solution:  def minOperationsQueries(      self,      n: int,      edges: list[list[int]],      queries: list[list[int]],  ) -> list[int]:    MAX = 26    m = math.ceil(math.log2(n))    graph = [[] for _ in range(n)]    # jump[i][j] := the 2^j-th ancestor of i    jump = [[0] * m for _ in range(n)]    # depth[i] := the depth of i    depth = [0] * n    # count[i][j] := the count of j from root to i, where 1 <= j <= 26    count = [[] for _ in range(n)]     for u, v, w in edges:      graph[u].append((v, w))      graph[v].append((u, w))     count[0] = [0] * (MAX + 1)    self._dfs(graph, 0, -1, jump, depth, count)     for j in range(1, m):      for i in range(n):        jump[i][j] = jump[jump[i][j - 1]][j - 1]     def getMinOperations(u: int, v: int) -> int:      """      Returns the minimum number of operations to make the edge weight      equilibrium between (u, v).      """      lca = self._getLCA(u, v, jump, depth)      # the number of edges between (u, v).      numEdges = depth[u] + depth[v] - 2 * depth[lca]      # the maximum frequency of edges between (u, v)      maxFreq = max(count[u][j] + count[v][j] - 2 * count[lca][j]                    for j in range(1, MAX + 1))      return numEdges - maxFreq     return [getMinOperations(u, v) for u, v in queries]   def _dfs(      self,      graph: list[list[tuple[int, int]]],      u: int,      prev: int,      jump: list[list[int]],      depth: list[int],      count: list[list[int]]  ) -> None:    for v, w in graph[u]:      if v == prev:        continue      jump[v][0] = u      depth[v] = depth[u] + 1      count[v] = count[u][:]      count[v][w] += 1      self._dfs(graph, v, u, jump, depth, count)   def _getLCA(      self,      u: int,      v: int,      jump: list[list[int]],      depth: list[int]  ) -> int:    """Returns the lca(u, v) by binary jump."""    # v is always deeper than u.    if depth[u] > depth[v]:      return self._getLCA(v, u, jump, depth)    # Jump v to the same height of u.    for j in range(len(jump[0])):      if depth[v] - depth[u] >> j & 1:        v = jump[v][j]    if u == v:      return u    # Jump u and v to the node right below the lca.    for j in range(len(jump[0]) - 1, -1, -1):      if jump[u][j] != jump[v][j]:        u = jump[u][j]        v = jump[v][j]    return jump[u][0] 

Did this explanation save you time? I'm a Grade 11 student building this free library to make difficult algorithms easier to understand.

Buy me a coffee ↗