Given a state diagram in the form of a linked list, where each node represents a unique character and has two pointers('next' and 'random'), and a string 'str', find if this string is acceptable by the state diagram or not.
The state diagram looks something like this:
A string is said to be acceptable if and only if it matches the flow of states character by character and ends at final state i.e. state with next equal to 'null'. For the below diagram 'c' is the final state.
Note 1. The random pointer of a node may point to NULL or to itself.
2. All the nodes will represent unique characters.
3. All the characters will be the lowercase alphabets.
4. You can assume that the first state is the first character of the string.
The first line contains a single integer 'T' that represents the number of test cases.
The first line of each test case will contain an integer ‘N’ denoting the number of states(nodes) in the state diagram.
The second line contains a string of length ‘N’ where the ith state represents the ith character of the string.
The third line contains 'N' integers a1, a2,....,an, where ai denotes the position to which the ith node’s random pointer points to. If the ith pointer points to NULL, then ai = -1.
The fourth line contains the string 'STR', which needs to be checked for the given state diagram.
Output Format:
Print “yes” in a single line if the string is acceptable by the given state diagram, “no” otherwise.
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 <= 26
1 <= ai <= N, or ai = -1(if pointing to NULL)
1 <= len(str) <= 10^5
Time Limit: 1 sec
1
4
abcd
1 4 2 4
abcbddd
yes
Notice that the state with character ‘b’ has its random pointer pointing to the state with the character ‘d’, and the state with the character ‘d’ (which is also the final state) has its random pointer pointing to itself.
The transitions will be as follows:
(next) (next) (random) (random) (random) (random)
a ----->b----->c------->b------>d ------>d ------>d(final state)
1
3
abc
3 2 -1
abcc
no
Implementation, try to do exactly as the problem statement says.
O(2^N), where ‘N’ is the length of the input string.
Since we are making two recursive calls in each iteration and so, the worst-case time complexity is O(2^N).
O(log(N)) where ‘N’ is the length of the string.
Since the recursion stack can grow logarithmically in the worst case depending on the length of the string and so, the total space complexity will be O(log(N)).