Ninjas is practicing problems on the linked list. He came across a problem in which he has given a linked list of ‘N’ nodes and an array ‘ARR’ of size ‘M’ that is the subset of the values present in the linked list. He has to print the number of connected components present in the array. Two values are said to be connected if they present next to each other in the linked list.
The first line of input contains an integer ‘T’, the number of test cases.
The first line of each test case contains the linked list separated by space and terminated by -1.
The second line of each test case contains an integer ‘M’, representing the size of the array ‘ARR’.
The third line of each test case contains ‘M’ space-separated integers, representing the array ‘ARR’.
Output Format :
For each test case, print the number of connected components.
Output for each test case will be printed in a separate line.
Note :
You do not need to print anything, it has already been taken care of. Just implement the given function.
1 <= T <= 10
1 <= N <= 3*10^3
1 <= M <= N
The linked list consists of unique integers only.
Time Limit: 1 sec
2
1 3 2 4 6 5 -1
2
1 3
1 3 7 4 -1
3
1 7 4
1
2
For the first test case :
1 3 appears consecutively in the linked list. So, they are connected.
Count: 1
For the second test case :
1 and 7 4 are connected.
Count: 2
2
1 3 4 5 -1
4
1 3 4 5
1 2 -1
1
1
1
1
Traverse the recursively linked list while checking whether the value is present in the array or not.
The idea is to traverse the linked list and check whether the value of the nodes is present in the array or not. We also use a map to store the values of the array so as to access them in constant time.
Here is the algorithm :
HELPER(TEMP, CHECK, MP):
O(N), where ‘N’ is the number of nodes in the linked list.
We traverse the linked list once recursively to count the number of connected components. Therefore, the overall time complexity will be O(N).
O(N), where ‘N’ is the number of nodes in the linked list.
The recursive stack can contain the length of the linked list. We also use a map to store the values present in the array which can be up to ‘N’. Therefore, the overall space complexity will be O(N).