Count of Root to Leaf Paths consisting of at most M consecutive Nodes having value K

• Difficulty Level : Easy
• Last Updated : 19 Jan, 2022

Given an Acyclic Undirected Graph in the form of a Binary Tree with the root at vertex 1 and values at each vertex [1, N] denoted by the array arr[], the task is to find the number of root to leaf paths that contain at most m consecutive nodes with value K.

Example:

Input: arr[] = {1, 0, 1, 0, 0, 1, 0}, K = 1, M = 2 Output:
Explanation:
Path 1 : 1 -> 2 -> 4 contains maximum 1 consecutive K
Path 2 : 1 -> 2 -> 5 contains maximum 1 consecutive K
Path 3 : 1 -> 3 -> 6 contains maximum 3 consecutive K
Path 4 : 1 -> 3 -> 7 contains maximum 2 consecutive K
Since the given value of M is 2, therefore there are 3 paths that contains atmost 2 consecutive K.

Input: arr[] = {2, 1, 3, 2, 1, 2, 1, 4, 3, 5, 2}, K = 2, M = 2

2
/     \
1       3
/   \    /  \
2     1  2    1
/  \   / \
4    3 5   2

Output: 3

Approach:
The problem can be solved using the Depth First Search approach:

• Depth First Search can be used to traverse all the paths from the root vertex.
• Every time, if the value at the present node is K, increment the count.
• Otherwise, set the count to 0.
• If the count exceeds M, then return.
• Otherwise, traverse its neighboring nodes and repeat the above steps.
• Finally, print the value of the count obtained.

Below is the implementation of the above approach:

Javascript


Output:
4

Time Complexity: O(V + E)
Auxiliary Space: O(V)

My Personal Notes arrow_drop_up