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:

  1. Every hop count is strictly greater than zero (a > 0), which excludes x, y, and z themselves.
  2. 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^5
  • len(edges) == n - 1
  • Every pair [u, v] in edges satisfies 1 <= u, v <= n, and the edges form a single valid tree.
  • 1 <= x, y, z <= n, and x, y, z are pairwise distinct.

Step-by-step walkthrough

  1. Understand the goal and the target trap

    Our input describes a tree — a connected, cycle-free graph with n nodes (1..n) and n - 1 bidirectional edges — along with three distinct reference nodes x, y, and z.

    For each candidate node v:

    1. Count the hops along the unique simple path connecting v to x, y, and z.
    2. Require every hop count to be strictly positive (> 0), which rules out x, y, and z right away.
    3. Order those three hop counts as a <= b <= c and test whether they form a Pythagorean triple: a^2 + b^2 = c^2 (such as 3^2 + 4^2 = 5^2).

    Skipping x, y, and z is essential, not just a shortcut. Suppose x sits halfway between y and z at distance b from each:

    y ----(b edges)---- x ----(b edges)---- z
    

    At vertex x, the three distances are (0, b, b). If we forgot to skip x, the equation 0^2 + b^2 = b^2 would evaluate to True and count x by mistake! Every other vertex is distinct from all three targets, so in a connected tree its three distances are automatically >= 1.

  2. Why searching from every vertex is too slow

    A natural first attempt is: for each candidate vertex v from 1 to n, run a Breadth-First Search (BFS) — a layer-by-layer graph search that visits nodes at distance 1, then distance 2, and so on — starting at v to find how far v is from x, y, and z.

    Each BFS can visit up to n vertices. Running a fresh BFS from all n vertices takes n * O(n) = O(n^2) work. With n = 100,000, n^2 is 10,000,000,000 steps, which will time out. Worse, almost all of that work is thrown away: each search explores the whole tree just to read three numbers.

  3. Key idea: run three BFS waves from the targets

    Because every edge in the tree is undirected, walking from v to x uses the exact same edges (in reverse) as walking from x to v:

    dist(v, x) == dist(x, v)
    dist(v, y) == dist(y, v)
    dist(v, z) == dist(z, v)
    

    Instead of launching n searches outward from every candidate vertex v, we flip the direction and launch just three BFS waves — one from x, one from y, and one from z:

    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..n
    

    One BFS starting at x computes dist_x[v] for every vertex v in O(n) time. Doing the same from y and z gives dist_y[v] and dist_z[v] for every vertex in 3 * O(n) = O(n) total time.

    We write the BFS iteratively using collections.deque (a double-ended queue supporting O(1) appends at the back and pops from the front) rather than recursive Depth-First Search (DFS). A tree of 100,000 vertices can be a single long chain 1 - 2 - 3 - ... - 100000, which would exceed Python's default recursion limit of 1,000 frames.

  4. Build the adjacency list and iterative BFS

    First, convert the raw edges list into an adjacency list adj, where adj[u] is a list of all vertices directly connected to u. Allocating n + 1 slots lets us index directly by vertex number 1..n without subtracting 1 everywhere.

    In bfs_distances, we initialize distances to -1 so -1 acts 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 distances
    
  5. Sort the three distances and count matches

    The problem does not promise which of x, y, or z is farthest from v — that can even change from one vertex v to another! So for each non-target vertex v, we sort [dist_x[v], dist_y[v], dist_z[v]] into a <= b <= c and check a * a + b * b == c * c using exact integer arithmetic (avoiding math.sqrt, which introduces floating-point rounding).

    Since n <= 10^5, the largest possible distance is n - 1 < 10^5, so c * 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_count
    
  6. Trace Example 1 step by step

    Let's sketch the tree from Example 1 (n = 7, reference nodes x = 5, y = 4, z = 6):

    1 --- 2 --- 3 --- 4(y) --- 5(x) --- 6(z)
          |
          7
    

    Running bfs_distances from x = 5, y = 4, and z = 6 populates 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   5
    

    Now 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 5 has distances (0, 1, 1) (0^2 + 1^2 == 1^2), confirming why excluding {x, y, z} is mandatory, and how node 1 had raw distances (4, 3, 5), confirming why sorting comes first. Nodes 1 and 7 qualify, so the function returns 2.

  7. 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):

  1. BFS from 5 produces dist_x = [_, 4, 3, 2, 1, 0, 1, 4].
  2. BFS from 4 produces dist_y = [_, 3, 2, 1, 0, 1, 2, 3].
  3. BFS from 6 produces dist_z = [_, 5, 4, 3, 2, 1, 0, 5].
  4. Skipping {4, 5, 6}, we test v = 1 ([3, 4, 5] -> 9 + 16 = 25, match!), v = 2 ([2, 3, 4] -> 13 != 16), v = 3 ([1, 2, 3] -> 5 != 9), and v = 7 ([3, 4, 5] -> 9 + 16 = 25, match!), returning 2.

Complexity

  • Time: O(n). Building the adjacency list (an array mapping each vertex to its list of direct neighbors) inspects each of the n - 1 edges once. Each of the three BFS traversals visits all n vertices and traverses all 2(n - 1) directed neighbor entries once. Finally, checking 1..n sorts a 3-element list (O(1) work) per vertex.
  • Space: O(n). The adjacency list stores 2(n - 1) neighbor entries across n + 1 lists, the three distance arrays hold n + 1 integers each, and the BFS queue holds at most n vertices at once.

Edge cases

  • Excluding x, y, and z: If x has equal distance b to both y and z, its sorted distances are (0, b, b) and 0^2 + b^2 = b^2 holds. 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 is 0.
  • Target order does not fix hypotenuse: Any of x, y, or z might be farthest from v, so sorting the three distances before testing a^2 + b^2 = c^2 is mandatory.
  • Non-primitive multiples: Scaled triples like (6, 8, 10) or (9, 12, 15) also satisfy a^2 + b^2 = c^2 and must be counted.
  • Overlapping paths in small trees: You do not need 3 + 4 + 5 + 1 = 13 vertices to get (3, 4, 5) — on a 6-vertex path 1-2-3-4-5-6 with targets 4, 5, 6, the paths from 1 share edges and still produce distances 3, 4, 5.
  • Deep chain trees (n = 10^5): A straight line of 100,000 vertices has depth 99,999, which crashes recursive DFS in Python (RecursionError around depth 1,000), whereas our iterative deque BFS 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]**2 without sorting: Misses valid vertices whenever x or y is the farthest target instead of z.
  • Adding edges in only one direction: [u, v] in edges is undirected; forgetting adj[v].append(u) leaves parts of the tree unreachable (distance = -1, whose square (-1)^2 = 1 corrupts checks!).
  • Using math.sqrt(a*a + b*b) == c: Introduces unnecessary floating-point operations when a * a + b * b == c * c is exact in integer math.
  • Using recursive DFS without raising the recursion limit: Fails on skewed or path-shaped trees with up to 10^5 nodes.

Alternative approaches

  • Iterative DFS with a Python list stack: Because a tree has a unique simple path between any two vertices, the first time any traversal reaches a vertex gives its exact distance. Replacing deque.popleft() with stack.pop() is also O(n) time and O(n) space.
  • Rooted tree + Lowest Common Ancestor (LCA): Root the tree at 1, record depth[v], and compute distances via depth[u] + depth[v] - 2 * depth[lca(u, v)], where Lowest Common Ancestor (LCA) is the deepest node that is an ancestor of both u and v. 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 set distances[neighbor] = distances[current] + weight in O(n) time. With positive integer weights, arithmetic stays exact (though in fixed-width 64-bit languages like C++ or Java, (n * max_weight)^2 could overflow int64 and require 128-bit integers). With floating-point weights, binary rounding makes == brittle, so compare using a small relative tolerance such as abs(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 in O(n log n) space so any distance dist(u, v) takes O(log n), or O(1) with an Euler tour + sparse table). Testing all n vertices per query would still cost O(n), so to go sublinear when landmarks are nearby, look at the union S of the three paths connecting x, y, and z (which forms a Y-shape meeting at one junction node). Every off-path vertex v hangs off its closest node p on S at some edge distance h >= 1, giving sorted distances (A + h, B + h, C + h) where 0 <= A <= B <= C are p's distances; expanding (A + h)^2 + (B + h)^2 = (C + h)^2 gives h^2 + 2(A + B - C)h + (A^2 + B^2 - C^2) = 0, which can have at most one positive integer solution h (a product of two positive roots would require A^2 + B^2 > C^2 while a positive sum of roots would require C > A + B, which is impossible for A, B >= 0). Precomputing subtree-depth counts via an Euler tour (flattening subtrees into contiguous array ranges) lets you count matching nodes hanging off each p in O(log n) time, answering queries in O(|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 by 4, forcing 1 <= a <= b <= c <= 4. Testing all positive integers 1 <= a <= b <= c <= 4 shows no solutions to a^2 + b^2 = c^2, because the smallest positive integer Pythagorean triple is (3, 4, 5), which requires c >= 5. Therefore at least one landmark must lie at distance >= 5 from v, making the diameter at least 5 (and diameter equal to 5 suffices, as shown in Example 1 where longest paths have 5 edges).

Follow-up questions

Similar questions

More IBM interview questions

All 27 IBM questions →