Right-Triangle Distance Vertices in a Tree
Trees & GraphsAuto-graded · 20 test casesLast updated
Compute distances in a tree from three marked vertices and count the other vertices whose three distances form a right-triangle (Pythagorean) triple.
Right-Triangle Distance Vertices
You are given a tree with n vertices labeled 1 through n. The tree is undirected and unweighted, and it is described by a list edges of n - 1 pairs. Each pair [u, v] is an edge joining u and v. You are also given three different marked vertices x, y and z.
Call a vertex v special if both of the following hold:
vis not one of the marked vertices (v != x,v != y,v != z). Equivalently, its distances to all three marked vertices are strictly positive.- Let the numbers of edges on the paths from
vtox,yandzbe sorted asa <= b <= c. Thena * a + b * b == c * c.
Return how many vertices of the tree are special.
Function
Implement count_special_vertices(n, edges, x, y, z), which returns a single integer.
Input
n: the number of vertices.edges: a list ofn - 1pairs[u, v], each an undirected edge.x,y,z: three pairwise distinct marked vertices.
Output
- An integer, the number of special vertices. If there are none, return
0.
Constraints
3 <= n <= 10^5len(edges) == n - 11 <= edges[i][0], edges[i][1] <= n- The edges form a valid connected tree.
1 <= x, y, z <= n, andx,y,zare pairwise distinct.- The tree may be a long chain, so a deeply recursive traversal can exceed the recursion limit.
Examples
Example 1
Input: count_special_vertices(8, [[1, 2], [2, 3], [3, 4], [4, 5], [5, 6], [3, 7], [7, 8]], 4, 8, 6)
Output: 1
Example 2
Input: count_special_vertices(4, [[1, 2], [2, 3], [3, 4]], 1, 2, 3)
Output: 0
Hints
Hint 1
Computing the distance from each vertex to each marked vertex with a separate search is too slow. Think about running a search from the marked vertices instead.
Hint 2
Run one breadth-first search from each of x, y and z. Together they give all three distances for every vertex in linear time.
Hint 3
Exclude the marked vertices explicitly, since a distance of 0 could otherwise satisfy a^2 + b^2 = c^2 with a = 0. Use an iterative traversal to avoid recursion depth problems.
Worked solution
Medium Try it yourself first — then compare your approach, complexity and edge cases.
Approach
Each vertex needs only three numbers: its distances to x, y and z. Searching for a path separately for every vertex would cost O(n^2) overall, which is too slow for n = 10^5.
Instead, run a breadth-first search from each marked vertex. This produces three arrays, dx, dy and dz, holding the distance from every vertex to x, y and z respectively. Then scan the vertices once:
- Skip the vertex if it is
x,yorz. - Sort its three distances into
a <= b <= c. - Count the vertex if
a*a + b*b == c*c.
Why it is correct
- BFS discovers vertices in non-decreasing order of edge count, so the first time a vertex is reached its distance is correct. In a tree the path between two vertices is unique, so this distance is the length of that path.
- Skipping the marked vertices enforces the "strictly positive" rule. Without it, a marked vertex with distances
(0, k, k)would pass the equation0 + k^2 = k^2and be counted wrongly. Every other vertex is at distance at least 1 from all three marked vertices. - After sorting, the largest value is
c, so the equation tests exactly the Pythagorean condition. Distances are below10^5, so squares stay below10^10, and Python integer arithmetic is exact. - BFS is iterative, so long chains do not cause recursion-depth errors.
Complexity
- Time: O(n). Building the adjacency list and each of the three BFS runs are linear, and the final scan does constant work per vertex.
- Space: O(n) for the adjacency list, the three distance arrays and the queue.
Reference solution
from collections import deque
from typing import List
def count_special_vertices(n: int, edges: List[List[int]], x: int, y: int, z: int) -> int:
graph = [[] for _ in range(n)]
for u, v in edges:
u -= 1
v -= 1
graph[u].append(v)
graph[v].append(u)
def distances_from(source: int) -> List[int]:
dist = [-1] * n
dist[source] = 0
queue = deque([source])
while queue:
node = queue.popleft()
for nxt in graph[node]:
if dist[nxt] == -1:
dist[nxt] = dist[node] + 1
queue.append(nxt)
return dist
dx = distances_from(x - 1)
dy = distances_from(y - 1)
dz = distances_from(z - 1)
count = 0
for i in range(n):
label = i + 1
if label == x or label == y or label == z:
continue
a, b, c = sorted((dx[i], dy[i], dz[i]))
if a * a + b * b == c * c:
count += 1
return count