#3585

Find Weighted Median Node in Tree

Hard
ArrayBinary SearchDynamic ProgrammingBit ManipulationTreeDepth-First SearchTree TraversalBinary Lifting
LeetCode ↗

Approaches

Brute ForceOptimal
Complexity Comparison
Brute ForceOptimal Solution
Time
O(n²)
O(n log n + q log n)
Space
O(1)
O(n)
💡

Intuition

Time O(n log n + q log n)Space O(n)

Utilize binary lifting and the lowest common ancestor (LCA) to efficiently find the path and compute the weighted median in logarithmic time.

⚙️

Algorithm

3 steps
  1. 1Step 1: Preprocess the tree to compute parent and weight information for binary lifting.
  2. 2Step 2: For each query, find the LCA of u and v.
  3. 3Step 3: Calculate the total weight and find the weighted median using the path from u to LCA and LCA to v.
solution.py3 lines
1def weightedMedianOptimal(n, edges, queries):
2    # Preprocess tree, find LCA, and compute median
3    return ans

Complexity note: Preprocessing takes O(n log n), each query takes O(log n) due to LCA.

  • 1Understanding LCA is crucial for efficient path queries.
  • 2Binary lifting allows quick ancestor retrieval.

Solutions and explanations are original Tejav content. Problem titles © LeetCode — use the LeetCode button above for the full problem statement.