VOOZH about

URL: https://www.geeksforgeeks.org/dsa/query-to-find-the-maximum-and-minimum-weight-between-two-nodes-in-the-given-tree-using-lca/

⇱ Query to find the maximum and minimum weight between two nodes in the given tree using LCA. - GeeksforGeeks


  • Courses
  • Tutorials
  • Interview Prep

Query to find the maximum and minimum weight between two nodes in the given tree using LCA.

Last Updated : 12 Jul, 2025

Given a tree, and the weights of all the node. Each query contains two integers u and v, the task is to find the minimum and maximum weight on the simple path between u and v (both inclusive).

Examples: 

Input: 
 

👁 Image


Query=[{1, 3}, {2, 4}, {3, 5}] 
Output: 
-1 5 
3 5 
-2 5 
Explanation: 
Weight on path 1 to 3 is [-1, 5, -1]. Hence, the minimum and maximum weight is -1 and 5 respectively. 
Weight on path 2 to 4 is [5, 3]. Hence, the minimum and maximum weight is 3 and 5 respectively. 
Weight on path 2 to 4 is [-1, 5, -1, -2]. Hence, the minimum and maximum weight is -2 and 5 respectively. 

Approach: The idea is to use LCA in a tree using Binary Lifting Technique. 

  • Binary Lifting is a Dynamic Programming approach where we pre-compute an array lca[i][j] where i = [1, n], j = [1, log(n)] and lca[i][j] contains 2j-th ancestor of node i. 
    • For computing the values of lca[][], the following recursion may be used

lca[i][j] = parent[i] if j = 0 and 
lca[i][j] = lca[lca[i][j – 1]][j – 1] if j > 0. 
 

  • As we will compute the lca[][] array we will also calculate the MinWeight[][] and MaxWeight[][] where MinWeight[i][j] contains the minimum weight from node i to its 2j-th ancestor, and MaxWeight[i][j] contains the maximum weight from node i to its 2j-th ancestor 
    • For computing the values of MinWeight[][] and MaxWeight[], the following recursion may be used.
  • After precomputation we find the minimum and maximum weight between (u, v) as we find the least common ancestor of (u, v).


 

Below is the implementation of the above approach:


 


Output
-1 5
3 5
-2 5

Time Complexity: The time taken in pre-processing is O(N logN) and every query takes O(logN) time. So the overall time complexity of the solution is O(N logN).
Auxiliary Space: O(MAX*log), for storing lca, where MAX=1000 and log=10.

Comment