Problem
Ask
Submissions

Problem: Closest Node to Path in Tree

Medium
30 min
Explore how to identify the closest node on a path between two nodes in a tree using breadth-first search techniques. Learn to handle queries that require finding nodes with minimal distances along paths and understand how to return the smallest indexed node when distances tie.

Statement

You are given a positive integer, n, representing the number of nodes in a tree, numbered from 00 to n1n-1. You are also given a 2D integer array edges of length n1n-1, where edges[i] =[ui,vi]= [u_i, v_i] indicates that there is a bidirectional edge connecting nodes uiu_i and viv_i.

You are also given a 2D integer array query of length mm, where query[i] =[starti,endi,nodei]= [start_i, end_i, node_i].

For each query i, find the node on the path between startistart_i and endiend_i that is closest to nodeinode_i in terms of the number of edges.

Return an integer array where the value at index ii corresponds to the answer for the ithi^{th} query.

Note: If there are multiple such nodes at the same minimum distance, return the one with the smallest index.

Constraints:

  • 11 \leq n 1000\leq 1000

  • edges.length ==n1== n - 1

  • edges[i].length ==2== 2

  • 0ui,vin10 \leq u_i, v_i \leq n-1

  • ui !=viu_i \space != v_i

  • 11 \leq query.length 1000\leq 1000

  • query[i].length ==3== 3

  • 0starti,endi,nodein10 \leq start_i, end_i, node_i \leq n-1

  • The graph is a tree.

Problem
Ask
Submissions

Problem: Closest Node to Path in Tree

Medium
30 min
Explore how to identify the closest node on a path between two nodes in a tree using breadth-first search techniques. Learn to handle queries that require finding nodes with minimal distances along paths and understand how to return the smallest indexed node when distances tie.

Statement

You are given a positive integer, n, representing the number of nodes in a tree, numbered from 00 to n1n-1. You are also given a 2D integer array edges of length n1n-1, where edges[i] =[ui,vi]= [u_i, v_i] indicates that there is a bidirectional edge connecting nodes uiu_i and viv_i.

You are also given a 2D integer array query of length mm, where query[i] =[starti,endi,nodei]= [start_i, end_i, node_i].

For each query i, find the node on the path between startistart_i and endiend_i that is closest to nodeinode_i in terms of the number of edges.

Return an integer array where the value at index ii corresponds to the answer for the ithi^{th} query.

Note: If there are multiple such nodes at the same minimum distance, return the one with the smallest index.

Constraints:

  • 11 \leq n 1000\leq 1000

  • edges.length ==n1== n - 1

  • edges[i].length ==2== 2

  • 0ui,vin10 \leq u_i, v_i \leq n-1

  • ui !=viu_i \space != v_i

  • 11 \leq query.length 1000\leq 1000

  • query[i].length ==3== 3

  • 0starti,endi,nodein10 \leq start_i, end_i, node_i \leq n-1

  • The graph is a tree.