19(March) Possible Paths in a Tree
19. Possible Paths in a Tree
The problem can be found at the following link: Question Link
Problem Description
Given a weighted tree with n nodes and (n-1) edges. You are given q queries. Each query contains a number x. For each query, find the number of paths in which the maximum edge weight is less than or equal to x.
Note: Path from A to B and B to A are considered to be the same.
Example 1:
Input:
n = 7
edges {start, end, weight} = {{1, 2, 3}, {2, 3, 1}, {2, 4, 9}, {3, 6, 7}, {3, 5, 8}, {5, 7, 4}}
q = 3
queries[] = {1, 3, 5}Output:
1 3 4Explanation:
Query 1: Path from 2 to 3
Query 2: Path from 1 to 2, 1 to 3, and 2 to 3
Query 3: Path from 1 to 2, 1 to 3, 2 to 3, and 5 to 7
My Approach
We'll initialize a
parentarray, aszarray, and aresvector to store the results.Initialize
ansto 0.Populate
parentandszarrays.Sort the edges based on weight.
Iterate over each edge and perform Union-Find operations, updating
ansaccordingly.Store the results of queries based on the maximum weight found in paths.
Return the result vector.
Time and Auxiliary Space Complexity
Expected Time Complexity: O(nlogn + qlogn), where n is the number of nodes and q is the number of queries. Sorting the edges and performing Union-Find operations both contribute to this complexity.
Expected Auxiliary Space Complexity: O(n), for storing the
parentandszarrays.
Code (C++)
Contribution and Support
For discussions, questions, or doubts related to this solution, feel free to connect on LinkedIn: Any Questions. Let’s make this learning journey more collaborative!
⭐ If you find this helpful, please give this repository a star! ⭐
📍Visitor Count
Last updated