Pythagorean Triple Nodes in a Tree
Medium · Coding & Algorithms · Software Engineer · Online Assessment
Problem Statement
Given a connected, acyclic undirected graph (a tree) containing n nodes labeled 1 through n and described by n - 1 bidirectional pairs in edges, you are also given three distinct reference nodes x, y, and z.
For any node v in the tree, measure the hop count (number of edges along the unique simple path) from v to x, from v to y, and from v to z. Sort those three hop counts in non-decreasing order as a <= b <= c. Node v qualifies as a Pythagorean node when both conditions below hold:
- Every hop count is strictly greater than zero (
a > 0), which excludesx,y, andzthemselves. - The squared hop counts satisfy
a^2 + b^2 = c^2.
Implement count_pythagorean_vertices(n, edges, x, y, z) and return how many nodes across 1..n qualify.
Examples
Example 1
Input:
n = 7
edges = [[1, 2], [2, 3], [3, 4], [4, 5], [5, 6], [2, 7]]
x = 5, y = 4, z = 6
Output: 2
Reference nodes 4, 5, and 6 are excluded because each has distance 0 to itself. Among the remaining nodes:
- Node 1 has hop counts (4, 3, 5) to (5, 4, 6). Sorted as [3, 4, 5], we get 3^2 + 4^2 = 9 + 16 = 25 = 5^2, so node 1 qualifies.
- Node 7 also connects directly to node 2, giving the same hop counts (4, 3, 5) and sorted triple [3, 4, 5], so node 7 qualifies as well.
- Node 2 has sorted hop counts [2, 3, 4] (4 + 9 != 16) and node 3 has [1, 2, 3] (1 + 4 != 9).
In total, 2 nodes satisfy both rules.
Example 2
Input:
n = 5
edges = [[1, 2], [1, 3], [1, 4], [4, 5]]
x = 2, y = 3, z = 5
Output: 0
Setting aside reference nodes 2, 3, and 5 leaves candidates 1 and 4. Node 1 has sorted hop counts [1, 1, 2] (1^2 + 1^2 = 2 != 2^2), while node 4 has sorted hop counts [1, 2, 2] (1^2 + 2^2 = 5 != 2^2). Neither forms a right-triangle triple, so the answer is 0.
Constraints
3 <= n <= 10^5len(edges) == n - 1- Every pair
[u, v]inedgessatisfies1 <= u, v <= n, and the edges form a single valid tree. 1 <= x, y, z <= n, andx,y,zare pairwise distinct.
Step-by-step walkthrough
Understand the goal and the target trap
Our input describes a tree — a connected, cycle-free graph with
nnodes (1..n) andn - 1bidirectional edges — along with three distinct reference nodesx,y, andz.For each candidate node
v:- Count the hops along the unique simple path connecting
vtox,y, andz. - Require every hop count to be strictly positive (
> 0), which rules outx,y, andzright away. - Order those three hop counts as
a <= b <= cand test whether they form a Pythagorean triple:a^2 + b^2 = c^2(such as3^2 + 4^2 = 5^2).
Skipping
x,y, andzis essential, not just a shortcut. Supposexsits halfway betweenyandzat distancebfrom each:y ----(b edges)---- x ----(b edges)---- zAt vertex
x, the three distances are(0, b, b). If we forgot to skipx, the equation0^2 + b^2 = b^2would evaluate toTrueand countxby mistake! Every other vertex is distinct from all three targets, so in a connected tree its three distances are automatically>= 1.- Count the hops along the unique simple path connecting
Why searching from every vertex is too slow
A natural first attempt is: for each candidate vertex
vfrom1ton, run a Breadth-First Search (BFS) — a layer-by-layer graph search that visits nodes at distance1, then distance2, and so on — starting atvto find how farvis fromx,y, andz.Each BFS can visit up to
nvertices. Running a fresh BFS from allnvertices takesn * O(n) = O(n^2)work. Withn = 100,000,n^2is10,000,000,000steps, which will time out. Worse, almost all of that work is thrown away: each search explores the whole tree just to read three numbers.Key idea: run three BFS waves from the targets
Because every edge in the tree is undirected, walking from
vtoxuses the exact same edges (in reverse) as walking fromxtov:dist(v, x) == dist(x, v) dist(v, y) == dist(y, v) dist(v, z) == dist(z, v)Instead of launching
nsearches outward from every candidate vertexv, we flip the direction and launch just three BFS waves — one fromx, one fromy, and one fromz:Naive (n searches): v1 -> {x, y, z}, v2 -> {x, y, z}, ..., vn -> {x, y, z} Flipped (3 searches): x -> all 1..n, y -> all 1..n, z -> all 1..nOne BFS starting at
xcomputesdist_x[v]for every vertexvinO(n)time. Doing the same fromyandzgivesdist_y[v]anddist_z[v]for every vertex in3 * O(n) = O(n)total time.We write the BFS iteratively using
collections.deque(a double-ended queue supportingO(1)appends at the back and pops from the front) rather than recursive Depth-First Search (DFS). A tree of100,000vertices can be a single long chain1 - 2 - 3 - ... - 100000, which would exceed Python's default recursion limit of1,000frames.Build the adjacency list and iterative BFS
First, convert the raw
edgeslist into an adjacency listadj, whereadj[u]is a list of all vertices directly connected tou. Allocatingn + 1slots lets us index directly by vertex number1..nwithout subtracting1everywhere.In
bfs_distances, we initializedistancesto-1so-1acts as both a "not visited yet" marker and a placeholder until the true distance is filled in.from collections import deque from typing import List def build_adjacency_list(n: int, edges: List[List[int]]) -> List[List[int]]: # adj[u] stores all neighbor vertices directly connected to u. # Index 0 is unused so 1-based vertex labels 1..n map directly to indices. adj: List[List[int]] = [[] for _ in range(n + 1)] for u, v in edges: # Tree edges are undirected, so record both directions. adj[u].append(v) adj[v].append(u) return adj def bfs_distances(adj: List[List[int]], source: int) -> List[int]: # distances[v] holds the edge count from source to v (-1 means unvisited). distances = [-1] * len(adj) distances[source] = 0 # Iterative FIFO queue of vertex IDs avoids Python's recursion limit on deep path trees. queue = deque([source]) while queue: current = queue.popleft() for neighbor in adj[current]: if distances[neighbor] == -1: distances[neighbor] = distances[current] + 1 queue.append(neighbor) return distancesSort the three distances and count matches
The problem does not promise which of
x,y, orzis farthest fromv— that can even change from one vertexvto another! So for each non-target vertexv, we sort[dist_x[v], dist_y[v], dist_z[v]]intoa <= b <= cand checka * a + b * b == c * cusing exact integer arithmetic (avoidingmath.sqrt, which introduces floating-point rounding).Since
n <= 10^5, the largest possible distance isn - 1 < 10^5, soc * c < 10^10— tiny and exact in Python integers.def is_pythagorean_triple(d1: int, d2: int, d3: int) -> bool: # Any of x, y, or z could be farthest, so sort to get a <= b <= c first. ordered = sorted([d1, d2, d3]) a = ordered[0] b = ordered[1] c = ordered[2] # Exact integer multiplication avoids floating-point rounding errors from sqrt(). return a * a + b * b == c * c def count_pythagorean_vertices(n: int, edges: List[List[int]], x: int, y: int, z: int) -> int: adj = build_adjacency_list(n, edges) # Distance in an undirected tree is symmetric: dist(v, target) == dist(target, v). # Three BFS runs give every vertex's distance to x, y, and z in O(n) total time. dist_x = bfs_distances(adj, x) dist_y = bfs_distances(adj, y) dist_z = bfs_distances(adj, z) pythagorean_count = 0 for vertex in range(1, n + 1): # Skip targets: a target has distance 0 to itself, and (0, b, b) would # falsely satisfy 0^2 + b^2 == b^2 even though distances must be > 0. if vertex == x or vertex == y or vertex == z: continue if is_pythagorean_triple(dist_x[vertex], dist_y[vertex], dist_z[vertex]): pythagorean_count += 1 return pythagorean_countTrace Example 1 step by step
Let's sketch the tree from Example 1 (
n = 7, reference nodesx = 5,y = 4,z = 6):1 --- 2 --- 3 --- 4(y) --- 5(x) --- 6(z) | 7Running
bfs_distancesfromx = 5,y = 4, andz = 6populates these three arrays:node: 1 2 3 4 5 6 7 dist_x: 4 3 2 1 0 1 4 dist_y: 3 2 1 0 1 2 3 dist_z: 5 4 3 2 1 0 5Now evaluate every node outside
{4, 5, 6}:node 1: sorted [3, 4, 5] -> 3^2 + 4^2 = 9 + 16 = 25 == 5^2 -> MATCH (count = 1) node 2: sorted [2, 3, 4] -> 2^2 + 3^2 = 4 + 9 = 13 != 4^2 -> no node 3: sorted [1, 2, 3] -> 1^2 + 2^2 = 1 + 4 = 5 != 3^2 -> no node 7: sorted [3, 4, 5] -> 3^2 + 4^2 = 9 + 16 = 25 == 5^2 -> MATCH (count = 2)Notice how node
5has distances(0, 1, 1)(0^2 + 1^2 == 1^2), confirming why excluding{x, y, z}is mandatory, and how node1had raw distances(4, 3, 5), confirming why sorting comes first. Nodes1and7qualify, so the function returns2.Complete solution
from typing import Any, Dict, List, Optional, Set, Tuple from collections import deque def build_adjacency_list(n: int, edges: List[List[int]]) -> List[List[int]]: # adj[u] stores all neighbor vertices directly connected to u. # Index 0 is unused so 1-based vertex labels 1..n map directly to indices. adj: List[List[int]] = [[] for _ in range(n + 1)] for u, v in edges: # Tree edges are undirected, so record both directions. adj[u].append(v) adj[v].append(u) return adj def bfs_distances(adj: List[List[int]], source: int) -> List[int]: # distances[v] holds the edge count from source to v (-1 means unvisited). distances = [-1] * len(adj) distances[source] = 0 # Iterative FIFO queue of vertex IDs avoids Python's recursion limit on deep path trees. queue = deque([source]) while queue: current = queue.popleft() for neighbor in adj[current]: if distances[neighbor] == -1: distances[neighbor] = distances[current] + 1 queue.append(neighbor) return distances def is_pythagorean_triple(d1: int, d2: int, d3: int) -> bool: # Any of x, y, or z could be farthest, so sort to get a <= b <= c first. ordered = sorted([d1, d2, d3]) a = ordered[0] b = ordered[1] c = ordered[2] # Exact integer multiplication avoids floating-point rounding errors from sqrt(). return a * a + b * b == c * c def count_pythagorean_vertices(n: int, edges: List[List[int]], x: int, y: int, z: int) -> int: adj = build_adjacency_list(n, edges) # Distance in an undirected tree is symmetric: dist(v, target) == dist(target, v). # Three BFS runs give every vertex's distance to x, y, and z in O(n) total time. dist_x = bfs_distances(adj, x) dist_y = bfs_distances(adj, y) dist_z = bfs_distances(adj, z) pythagorean_count = 0 for vertex in range(1, n + 1): # Skip targets: a target has distance 0 to itself, and (0, b, b) would # falsely satisfy 0^2 + b^2 == b^2 even though distances must be > 0. if vertex == x or vertex == y or vertex == z: continue if is_pythagorean_triple(dist_x[vertex], dist_y[vertex], dist_z[vertex]): pythagorean_count += 1 return pythagorean_count✅ Submit now — all tests should pass.
Intuition & how it works
Imagine a town of 100,000 houses connected by footpaths, and you want to know how many houses have distances (a, b, c) to the school (x), the park (y), and the train station (z) that satisfy a^2 + b^2 = c^2. Instead of asking every single resident to walk out and measure routes to all three landmarks, you can station one messenger at each of the three landmarks and have each messenger walk outward once, jotting down the step count to every house they pass. Because footpaths work in both directions, the distance from a house to the school is identical to the distance from the school to that house.
The naive approach starts a separate search from every vertex v in 1..n to find x, y, and z. In a tree of n vertices, one search takes O(n) steps, so n searches take O(n^2) — roughly 10^10 operations when n = 10^5, which is far too slow. Worse, each search explores nearly the whole tree only to extract three numbers.
By reversing the perspective, we run Breadth-First Search (BFS) — a level-by-level graph traversal using a first-in, first-out queue — just three times: once from x, once from y, and once from z. Consider Example 1 (1 - 2 - 3 - 4 - 5 - 6 with extra branch 2 - 7 and x = 5, y = 4, z = 6):
- BFS from
5producesdist_x = [_, 4, 3, 2, 1, 0, 1, 4]. - BFS from
4producesdist_y = [_, 3, 2, 1, 0, 1, 2, 3]. - BFS from
6producesdist_z = [_, 5, 4, 3, 2, 1, 0, 5]. - Skipping
{4, 5, 6}, we testv = 1([3, 4, 5]->9 + 16 = 25, match!),v = 2([2, 3, 4]->13 != 16),v = 3([1, 2, 3]->5 != 9), andv = 7([3, 4, 5]->9 + 16 = 25, match!), returning2.
Complexity
- Time: O(n). Building the adjacency list (an array mapping each vertex to its list of direct neighbors) inspects each of the
n - 1edges once. Each of the three BFS traversals visits allnvertices and traverses all2(n - 1)directed neighbor entries once. Finally, checking1..nsorts a 3-element list (O(1)work) per vertex. - Space: O(n). The adjacency list stores
2(n - 1)neighbor entries acrossn + 1lists, the three distance arrays holdn + 1integers each, and the BFS queue holds at mostnvertices at once.
Edge cases
- Excluding
x,y, andz: Ifxhas equal distancebto bothyandz, its sorted distances are(0, b, b)and0^2 + b^2 = b^2holds. Skipping{x, y, z}explicitly prevents false positives. - Minimum size
n = 3: All three vertices are targets, so zero candidate vertices remain and the answer is0. - Target order does not fix hypotenuse: Any of
x,y, orzmight be farthest fromv, so sorting the three distances before testinga^2 + b^2 = c^2is mandatory. - Non-primitive multiples: Scaled triples like
(6, 8, 10)or(9, 12, 15)also satisfya^2 + b^2 = c^2and must be counted. - Overlapping paths in small trees: You do not need
3 + 4 + 5 + 1 = 13vertices to get(3, 4, 5)— on a 6-vertex path1-2-3-4-5-6with targets4, 5, 6, the paths from1share edges and still produce distances3, 4, 5. - Deep chain trees (
n = 10^5): A straight line of100,000vertices has depth99,999, which crashes recursive DFS in Python (RecursionErroraround depth1,000), whereas our iterativedequeBFS runs smoothly.
Common mistakes
- Forgetting to skip the three targets: Counts any target that happens to be equidistant from the other two targets (
0^2 + b^2 == b^2). - Checking
dist_x[v]**2 + dist_y[v]**2 == dist_z[v]**2without sorting: Misses valid vertices wheneverxoryis the farthest target instead ofz. - Adding edges in only one direction:
[u, v]inedgesis undirected; forgettingadj[v].append(u)leaves parts of the tree unreachable (distance = -1, whose square(-1)^2 = 1corrupts checks!). - Using
math.sqrt(a*a + b*b) == c: Introduces unnecessary floating-point operations whena * a + b * b == c * cis exact in integer math. - Using recursive DFS without raising the recursion limit: Fails on skewed or path-shaped trees with up to
10^5nodes.
Alternative approaches
- Iterative DFS with a Python
liststack: Because a tree has a unique simple path between any two vertices, the first time any traversal reaches a vertex gives its exact distance. Replacingdeque.popleft()withstack.pop()is alsoO(n)time andO(n)space. - Rooted tree + Lowest Common Ancestor (LCA): Root the tree at
1, recorddepth[v], and compute distances viadepth[u] + depth[v] - 2 * depth[lca(u, v)], where Lowest Common Ancestor (LCA) is the deepest node that is an ancestor of bothuandv. For a single(x, y, z)triple, this requires more code and is no faster than three simple BFS passes.
Follow-up questions
- What changes are needed if each tree edge carries a positive integer or floating-point weight instead of weight 1? Because a tree has only one simple path between any two vertices, you still do not need Dijkstra's algorithm (a priority-queue shortest-path search that costs
O(n log n)). Store(neighbor, weight)pairs in the adjacency list, and during each of the three traversals setdistances[neighbor] = distances[current] + weightinO(n)time. With positive integer weights, arithmetic stays exact (though in fixed-width 64-bit languages like C++ or Java,(n * max_weight)^2could overflowint64and require 128-bit integers). With floating-point weights, binary rounding makes==brittle, so compare using a small relative tolerance such asabs(a * a + b * b - c * c) <= 1e-9 * c * c. - Suppose the tree is static and we must answer Q separate queries of landmark triples (x, y, z); how can we speed up per-query runtime? First, precompute node depths and an LCA table (for example via binary lifting, which stores
2^k-th ancestors inO(n log n)space so any distancedist(u, v)takesO(log n), orO(1)with an Euler tour + sparse table). Testing allnvertices per query would still costO(n), so to go sublinear when landmarks are nearby, look at the unionSof the three paths connectingx,y, andz(which forms a Y-shape meeting at one junction node). Every off-path vertexvhangs off its closest nodeponSat some edge distanceh >= 1, giving sorted distances(A + h, B + h, C + h)where0 <= A <= B <= Carep's distances; expanding(A + h)^2 + (B + h)^2 = (C + h)^2givesh^2 + 2(A + B - C)h + (A^2 + B^2 - C^2) = 0, which can have at most one positive integer solutionh(a product of two positive roots would requireA^2 + B^2 > C^2while a positive sum of roots would requireC > A + B, which is impossible forA, B >= 0). Precomputing subtree-depth counts via an Euler tour (flattening subtrees into contiguous array ranges) lets you count matching nodes hanging off eachpinO(log n)time, answering queries inO(|S| log n). - Can any node ever satisfy the Pythagorean condition when the tree's diameter is 4 or smaller? No. A tree's diameter is the longest distance between any pair of vertices in the tree, so when the diameter is at most
4, every pairwise distance is bounded by4, forcing1 <= a <= b <= c <= 4. Testing all positive integers1 <= a <= b <= c <= 4shows no solutions toa^2 + b^2 = c^2, because the smallest positive integer Pythagorean triple is(3, 4, 5), which requiresc >= 5. Therefore at least one landmark must lie at distance>= 5fromv, making the diameter at least5(and diameter equal to5suffices, as shown in Example 1 where longest paths have5edges).
Follow-up questions
- What changes are needed if each tree edge carries a positive integer or floating-point weight instead of weight 1?
- Suppose the tree is static and we must answer Q separate queries of landmark triples (x, y, z); how can we speed up per-query runtime?
- Can any node ever satisfy the Pythagorean condition when the tree's diameter is 4 or smaller?
Similar questions
- Eliminate Adjacent Identical Letters
- Total Revenue from Highest-Stock VM Allocation
- Active Employees With Unbroken Badge Renewals
- Bounded-Range Index Triplet Count
- Minimum Substitutions to Break Character Triples
- Counting Price-Matched Seat Trios
More IBM interview questions
- Report Accounts With High Mean Resource Utilization Medium
- Fixed-TTL Session Token Manager Medium
- One-Way Video Behavioral Assessment: Six Timed Engineering Prompts Medium Pro
- Active Employees With Unbroken Badge Renewals Medium Pro
- Bounded-Range Index Triplet Count Medium Pro
- Counting Price-Matched Seat Trios Medium Pro
- Consistent Sensor Trio Count Medium Pro
- Harden an In-Memory Event Ticket Reservation Service Medium Pro
- End-to-End B2B Lead Prioritization and Scoring System Easy Pro
- Measuring Trial-to-Paid Conversion Probability Easy Pro