1. Introduction
In this article, we will understand how to solve the Count Tree Paths With Limited Max Edge Weight problem using C#.
This problem is based on three important concepts:
Tree – A connected graph without cycles.
Sorting – Processing edges based on their weights.
Disjoint Set Union (DSU) – Managing connected components efficiently.
The main challenge is to count all possible distinct paths between two different nodes where the maximum edge weight along the path does not exceed the given query value.
Instead of checking every possible path, we use DSU to calculate the answer efficiently.
2. Understanding the problem
We are given:
n– Number of nodes.edges– Connections between nodes with weights.queries– Maximum allowed edge weights.
For every query x, we need to count the number of distinct paths where every edge in the path has a weight less than or equal to x.
Remember:
A path from 1 to 2 is the same as a path from 2 to 1.
A node cannot form a path with itself.
A path must contain at least one edge.
Example 1
Input:
n = 3;
edges = new int[][]
{
new int[] { 1, 2, 1 },
new int[] { 2, 3, 4 }
};
queries = new int[] { 3 };Tree representation:
Allowed edge
Not allowed edge
Query = 3.
Only the edge with weight 1 is allowed.
Valid paths:
- 1 → 2
The path 1 → 3 is not allowed because it contains an edge with weight 4.
Output:
[1]3. Understand the important mathematical concept
This is the most important part of the problem.
Suppose we have two separate connected components:
Component A: Component B:
1 ---- 2 4 ---- 5 ---- 6Component A has 2 nodes.
Component B has 3 nodes.
Now, if we connect these components using a new edge:
1 ---- 2 ---- 4 ---- 5 ---- 6How many new paths are created?
Every node in Component A can form a path with every node in Component B.
Component A | Component B | New path |
|---|---|---|
1 | 4 | 1 → 4 |
1 | 5 | 1 → 5 |
1 | 6 | 1 → 6 |
2 | 4 | 2 → 4 |
2 | 5 | 2 → 5 |
2 | 6 | 2 → 6 |
Total new paths:
\[ 2 \times 3 = 6 \]
Therefore, the formula is:
\[ \boxed{NewPaths = SizeA \times SizeB} \]
We use this formula whenever two different connected components are merged.
4. What is Disjoint Set Union (DSU)?
DSU stands for Disjoint Set Union. It is also known as Union-Find.
It is used to manage multiple independent groups of nodes.
DSU has two important operations:
1. Find()
Finds the root or representative of a node's component.
2. Union()
Combines two different components into one component.
Initially
Every node belongs to its own component.
1 2 3 4 5Parent array:
parent = [1, 2, 3, 4, 5]Component sizes:
size = [1, 1, 1, 1, 1]After Union(1, 2)
1 ---- 2 3 4 5Now nodes 1 and 2 belong to the same component.
After Union(2, 3)
1 ---- 2 ---- 3 4 5Now the component contains three nodes.
Its size is 3.
This is how DSU maintains connected components.
5. Important DSU optimizations
We use two optimizations to make the algorithm efficient.
A. Path Compression
Consider this parent relationship:
1 → 2 → 3 → 4When we call:
Find(1);The root is node 4.
Path compression updates the parent relationships so that future Find operations become faster.
int Find(int x)
{
if (parent[x] != x)
{
parent[x] = Find(parent[x]);
}
return parent[x];
}Explanation:
Check whether the current node is its own parent.
If not, recursively find its root.
Update its parent directly to the root.
Return the root.
B. Union by Size
When merging two components, we attach the smaller component to the larger component.
if (size[rootA] < size[rootB])
{
int temp = rootA;
rootA = rootB;
rootB = temp;
}
parent[rootB] = rootA;
size[rootA] += size[rootB];Why?
Because attaching smaller trees under larger trees helps keep the DSU structure shallow.
6. Complete C# solution
Now let's combine everything into the requested class.
class Solution
{
int[] parent;
int[] size;
// Find the root parent of a node
int Find(int x)
{
if (parent[x] != x)
{
parent[x] = Find(parent[x]);
}
return parent[x];
}
// Merge two connected components
void Union(int a, int b, ref int totalPaths)
{
int rootA = Find(a);
int rootB = Find(b);
// Already in the same component
if (rootA == rootB)
{
return;
}
// Count new paths
totalPaths += size[rootA] * size[rootB];
// Union by Size
if (size[rootA] < size[rootB])
{
int temp = rootA;
rootA = rootB;
rootB = temp;
}
parent[rootB] = rootA;
size[rootA] += size[rootB];
}
public List<int> maximumWeight(
int n, int[][] edges, int[] queries)
{
// Sort edges based on weight
Array.Sort(edges,
(a, b) => a[2].CompareTo(b[2]));
// Sort query indexes
int q = queries.Length;
int[] indexes = new int[q];
for (int i = 0; i < q; i++)
{
indexes[i] = i;
}
Array.Sort(indexes,
(a, b) => queries[a].CompareTo(queries[b]));
// Initialize DSU
parent = new int[n + 1];
size = new int[n + 1];
for (int i = 1; i <= n; i++)
{
parent[i] = i;
size[i] = 1;
}
int[] answer = new int[q];
int edgeIndex = 0;
int totalPaths = 0;
// Process queries in sorted order
foreach (int queryIndex in indexes)
{
int limit = queries[queryIndex];
// Process all eligible edges
while (edgeIndex < edges.Length &&
edges[edgeIndex][2] <= limit)
{
int u = edges[edgeIndex][0];
int v = edges[edgeIndex][1];
Union(u, v, ref totalPaths);
edgeIndex++;
}
// Save answer in original query order
answer[queryIndex] = totalPaths;
}
return new List<int>(answer);
}
}7. Detailed explanation of the code
Let's understand the solution section by section.
Step 1: Declare DSU arrays
int[] parent;
int[] size;parent[] stores the parent of every node.
size[] stores the number of nodes in each component's root.
For example:
parent[1] = 1
size[1] = 3This means node 1 is the root of a component containing three nodes.
Step 2: Sort edges
Array.Sort(edges,
(a, b) => a[2].CompareTo(b[2]));Why do we sort?
Because we want to process edges from the smallest weight to the largest weight.
Example:
Before sorting:
[1, 2, 3]
[2, 3, 1]
[2, 4, 9]
[5, 7, 4]After sorting:
[2, 3, 1]
[1, 2, 3]
[5, 7, 4]
[2, 4, 9]This allows us to process eligible edges without repeatedly checking all edges.
Step 3: Sort query indexes
int[] indexes = new int[q];
for (int i = 0; i < q; i++)
{
indexes[i] = i;
}We store the original positions of queries instead of modifying the query array.
For example:
queries = [5, 1, 3]
indexes = [0, 1, 2]Then:
Array.Sort(indexes,
(a, b) => queries[a].CompareTo(queries[b]));After sorting:
indexes = [1, 2, 0]This represents:
Query 1 → Original index 1
Query 3 → Original index 2
Query 5 → Original index 0This is called sorting queries indirectly using their indexes.
Step 4: Initialize DSU
parent = new int[n + 1];
size = new int[n + 1];
for (int i = 1; i <= n; i++)
{
parent[i] = i;
size[i] = 1;
}Every node starts as an independent component.
Since the nodes are numbered from 1 to n, we allocate arrays of size n + 1.
Step 5: Process queries
foreach (int queryIndex in indexes)
{
int limit = queries[queryIndex];We process the queries in ascending order.
For every query, we get its maximum allowed edge weight.
Step 6: Process eligible edges
while (edgeIndex < edges.Length &&
edges[edgeIndex][2] <= limit)This is the core condition.
It checks:
Are there any remaining edges?
Is the current edge weight less than or equal to the query limit?
If both conditions are true, we merge the components.
int u = edges[edgeIndex][0];
int v = edges[edgeIndex][1];
Union(u, v, ref totalPaths);
edgeIndex++;Notice that edgeIndex is declared outside the query loop.
This is important because each edge is processed only once.
Step 7: Store the answer
answer[queryIndex] = totalPaths;We store the result using the original query index.
This ensures that the returned output matches the input query order.
8. Complete dry run
Consider the following input:
n = 7;
edges = new int[][]
{
new int[] { 1, 2, 3 },
new int[] { 2, 3, 1 },
new int[] { 2, 4, 9 },
new int[] { 3, 6, 7 },
new int[] { 3, 5, 8 },
new int[] { 5, 7, 4 }
};
queries = new int[] { 1, 3, 5 };Sorted edges:
Edge | Weight |
|---|---|
2–3 | 1 |
1–2 | 3 |
5–7 | 4 |
3–6 | 7 |
3–5 | 8 |
2–4 | 9 |
Query 1: Limit = 1
Merge nodes 2 and 3.
2 ---- 3Calculation:
\[ 1 \times 1 = 1 \]
Total paths = 1.
Query 2: Limit = 3
Merge nodes 1 and 2.
1 ---- 2 ---- 3Component sizes are 1 and 2.
\[ 1 \times 2 = 2 \]
Total paths:
\[ 1 + 2 = 3 \]
Query 3: Limit = 5
Merge nodes 5 and 7.
1 ---- 2 ---- 3 5 ---- 7Component sizes are 1 and 1.
\[ 1 \times 1 = 1 \]
Total paths:
\[ 3 + 1 = 4 \]
Final result
1Query 1
3Query 3
4Query 5
[1, 3, 4]9. Why does this algorithm work?
The important observation is that a tree has exactly one unique path between any two different nodes.
For a given query, consider only the edges whose weights are less than or equal to that query.
These edges form a collection of connected components.
If two nodes are in the same component, their unique tree path uses only eligible edges.
If two nodes are in different components, their path cannot satisfy the query.
Therefore, counting all pairs inside each connected component gives the exact number of valid paths.
When two components of sizes a and b are merged, exactly a × b new node pairs become connected.
This proves why the DSU counting formula works.
10. Time and space complexity
Let n be the number of nodes and q be the number of queries.
Operation | Complexity |
|---|---|
Sort edges | O(n log n) |
Sort query indexes | O(q log q) |
Initialize DSU | O(n) |
Process edges | O(n α(n)) |
Process queries | O(q) |
Overall time complexity:
\[ \boxed{O(n\log n + q\log q)} \]
Auxiliary space complexity:
\[ \boxed{O(n+q)} \]
The DSU arrays require O(n), while query indexes and answers require O(q).
The expected O(n) auxiliary-space description generally excludes the query sorting/index and output storage.
11. Common mistakes to avoid
Not sorting edges: You may process an edge with a large weight before a smaller one.
Not sorting queries: You lose the advantage of processing every edge only once.
Using the original query index incorrectly: Always store answers at
answer[queryIndex].Forgetting component sizes: Without component sizes, you cannot calculate newly created paths.
Counting already-connected components: If both roots are equal, no new paths are created.
Using
<instead of<=: The problem allows edges whose weight is exactly equal to the query limit.
12. Interview revision – Important points
Question | Answer |
|---|---|
Which algorithm is used? | DSU |
Why sort edges? | Process by increasing weight |
Why sort queries? | Process queries efficiently |
What does Find do? | Finds component root |
What does Union do? | Merges components |
Why maintain size? | Counts new paths |
What is the formula? | sizeA × sizeB |
Why use original indexes? | Preserve output order |
What is the overall time? | O(n log n + q log q) |


Join the conversation! Your thoughts help the community grow.