Length of Longest increasing sequence of nodes in a given Graph
Given a graph root, the task is to find the length of the longest increasing sequence in the graph.
Attention reader! Don’t stop learning now. Get hold of all the important DSA concepts with the DSA Self Paced Course at a student-friendly price and become industry ready. To complete your preparation from learning a language to DS Algo and many more, please refer Complete Interview Preparation Course.
Input: root = 7—-17
/ \ \
Explanation: The longest increasing sequence in the graph consists of the nodes 1, 2, 5, 6, 8, 12
Approach: The given problem can be solved by using the depth-first search on every node in the graph. The idea is to use recursion and visit the neighbor nodes with values less than the current node and calculate the longest path ending up to the neighbors before calculating the longest path ending up to the current node. Below steps can be followed to solve the problem:
- Apply depth-first search on the root node to visit and store all the nodes in a list
- Use recursion to apply depth-first search on every unvisited node of the graph and use a hashmap to store the visited nodes of the graph mapping to the longest path ending up to that node
- At every node iterate through the ArrayList of neighbors and use recursion on the neighbor nodes with a value less than the current node’s value and calculate the longest path ending at them
- Find the maximum of the longest path ending up to the neighbors and add 1 to it for calculating the longest path ending up to the current node
- Return the maximum of all longest paths
Below is the implementation of the above approach:
Time Complexity: O(V + E), where V is the number of vertices and E is the number of edges
Auxiliary Space: O(V)