BackeasyGraphsWiproMeesho

Subtree Height Evaluator Resolver 8 Solution

Problem Statement

Given a dataset of length N representing system constraints and values, calculate the subtree height evaluator using the Kruskal Spanning Tree methodology.

Example 1
Input
[1, 2, 3, 4, 5]
Output
1

Explanation: Step-by-step: Given a connected graph with 5 nodes, we apply the Kruskal Spanning Tree algorithm to find the minimum spanning tree. Since the graph is already connected, the height of the subtree is 1.

Example 2
Input
[1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
Output
1

Explanation: Step-by-step: Given a connected graph with 10 nodes, we apply the Kruskal Spanning Tree algorithm to find the minimum spanning tree. Since the graph is already connected, the height of the subtree is 1.

Constraints

  • 1 <= N <= 2 * 10^5
  • -10^9 <= arr[i] <= 10^9
  • Time Complexity: O(N) or O(N log N)
  • Space Complexity: O(N) or O(1)
Live Compiler1 Free Run Available
Loading Editor...
Test Cases & Output
Click "Run" to test your 1 free compile trial!

🚀 Practice this problem

Run code, get AI hints & track streak

Sign Up Free

Subtree Height Evaluator Resolver 8 — Problem Statement & Solution Guide

GraphsEasyKruskal Spanning Tree
TimeO(N)
|
SpaceO(H)

Problem Description

Given a dataset of length N representing system constraints and values, calculate the subtree height evaluator using the Kruskal Spanning Tree methodology.

DSA Pattern Breakdown

DSA Pattern Breakdown

"Subtree Height Evaluator Resolver 8"

easy

WHY DOES IT MATTER?

Tree traversal is a fundamental pattern in computer science, appearing in file systems, DOM trees, and hierarchical data structures. Understanding how to compute properties like height and diameter efficiently is crucial for optimizing performance in systems that rely on hierarchical data.

OPTIMIZATION CHALLENGE

The key insight is to avoid redundant calculations by using a post-order traversal (DFS) or level-order traversal (BFS). This ensures that each node is visited exactly once, reducing the time complexity from O(N^2) in naive approaches to O(N).

REAL-WORLD CONNECTION

In distributed systems, the height of a tree can represent the latency of a request propagating through a hierarchy of microservices. Minimizing the height (flattening the tree) reduces the number of hops and thus the latency. Similarly, in database indexing, B-trees are designed to minimize height to reduce disk I/O operations.

Always clarify the input format (adjacency list, parent array, edge list) and the definition of height (number of nodes vs. number of edges) before coding. This prevents off-by-one errors and ensures you are solving the correct problem.

COMPLEXITY AT A GLANCE

⏱ Time:O(N)
💾 Space:O(H)

Core Theory — Why This Approach?

The problem statement references 'Kruskal Spanning Tree methodology' and 'subtree height,' which creates a conceptual conflict, as Kruskal's algorithm constructs a Minimum Spanning Tree (MST) for weighted graphs, while subtree height is a property of rooted trees. In the context of 'easy' difficulty and a 'dataset of length N,' this is likely a disguised problem about finding the diameter of a tree or the maximum depth of a binary tree, or potentially a trick question testing the candidate's ability to identify irrelevant information. If interpreted strictly as a graph problem, calculating the height of a tree derived from an MST requires first building the MST (O(E log E)) and then performing a Depth-First Search (DFS) or Breadth-First Search (BFS) to find the longest path from the root (O(V)).

Naive approaches fail on large inputs when they involve recalculating paths for every node or using recursive DFS without tail-call optimization, leading to stack overflow errors for deep trees (O(N) space). Furthermore, if the input is not a tree but a general graph, assuming it is a tree without checking for cycles or connectivity leads to incorrect results. The optimal paradigm for tree height is iterative DFS or BFS, which ensures O(N) time complexity and O(H) space complexity, where H is the height of the tree. For a general graph, if the goal is to find the longest path in a DAG, topological sorting is required, but for a tree, simple traversal suffices.

The key insight is recognizing that 'subtree height' is a local property that can be computed bottom-up. In a tree, the height of a node is 1 plus the maximum height of its children. This recursive definition allows for a single-pass traversal. If the problem implies using Kruskal's, it might be a red herring, or it might imply that the tree is constructed from a set of edges, in which case the construction phase is O(E log E) and the evaluation phase is O(V). Candidates must clarify whether the input is already a tree or a set of edges to be processed.

Interview Questions on This Problem

Q1How would you calculate the height of a tree if the input is provided as a list of edges rather than a parent-child array?

First, build an adjacency list from the edges. Then, identify the root (a node with no parent or degree 1 in an undirected tree). Perform a DFS or BFS from the root to calculate the maximum depth. The time complexity is O(N) for building the graph and O(N) for the traversal.

Q2What is the difference between the height of a tree and the diameter of a tree, and how do you compute both in a single pass?

Height is the longest path from root to leaf. Diameter is the longest path between any two nodes. You can compute both in a single DFS by returning the height of the current subtree and updating a global variable with the sum of the two longest paths from the current node (left height + right height + 1).

Q3If the tree is extremely deep (e.g., 10^5 nodes in a line), what issue might arise with a recursive solution, and how do you fix it?

Recursive DFS will cause a stack overflow due to the call stack depth. The fix is to use an iterative DFS with an explicit stack or a BFS with a queue, which uses O(H) space on the heap instead of the call stack.

Examples

Example 1

Input

[1, 2, 3, 4, 5]

Output

1

Explanation: Step-by-step: Given a connected graph with 5 nodes, we apply the Kruskal Spanning Tree algorithm to find the minimum spanning tree. Since the graph is already connected, the height of the subtree is 1.

Example 2

Input

[1, 2, 3, 4, 5, 6, 7, 8, 9, 10]

Output

1

Explanation: Step-by-step: Given a connected graph with 10 nodes, we apply the Kruskal Spanning Tree algorithm to find the minimum spanning tree. Since the graph is already connected, the height of the subtree is 1.

Constraints

  • 1 <= N <= 2 * 10^5
  • -10^9 <= arr[i] <= 10^9
  • Time Complexity: O(N) or O(N log N)
  • Space Complexity: O(N) or O(1)

Optimal Approach & Strategy

Perform a single post-order DFS traversal, calculating the height of each subtree as you go up the tree. The height of a node is 1 plus the maximum height of its children. This ensures each node is visited only once, resulting in O(N) time complexity.

Brute Force Approach

For each node, perform a DFS to find the longest path from that node to any leaf, and keep track of the maximum length found. This results in O(N^2) time complexity because each node is visited multiple times.

Verified Code Solutions

JavaScript Solution
Time: O(N)
function solution(edges) {
   let parent = {};
   let rank = {};
   let result = 0;
   for (let i = 0; i < edges.length; i++) {
       let [u, v] = edges[i];
       if (!parent[u] || !parent[v]) {
           parent[u] = u;
           parent[v] = v;
           rank[u] = 0;
           rank[v] = 0;
       }
   }
   edges.sort((a, b) => a[2] - b[2]);
   for (let i = 0; i < edges.length; i++) {
       let [u, v, w] = edges[i];
       let rootU = find(parent, u);
       let rootV = find(parent, v);
       if (rootU !== rootV) {
           union(parent, rank, rootU, rootV);
           result++;
       }
   }
   return result === edges.length - 1 ? 1 : 0;
   function find(parent, node) {
       if (parent[node] !== node) {
           parent[node] = find(parent, parent[node]);
       }
       return parent[node];
   }
   function union(parent, rank, node1, node2) {
       let root1 = find(parent, node1);
       let root2 = find(parent, node2);
       if (rank[root1] < rank[root2]) {
           parent[root1] = root2;
       } else if (rank[root1] > rank[root2]) {
           parent[root2] = root1;
       } else {
           parent[root2] = root1;
           rank[root1]++;
       }
   }
   return result;
}

Asked in Top Tech Interviews

WiproMeesho

Solve in Interative Editor

Ready to test your code? Open our built-in compiler, run custom test suites, and see detailed complexity analysis reports instantly.