![]() |
VOOZH | about |
Given two linked lists, the task is to check whether the first list is present in 2nd list or not.
Examples:
Input: list1 = 10->20, list2 = 5->10->20
Output : Yes
Explanation: 5 -> 10 -> 20Input: list1 = 1->2, list2 = 1->2->1->2->3->4
Output: Yes
Explanation: 1 -> 2 -> 1 -> 2 -> 3 -> 4Input: list1 = 1->2->3->4, list2 = 1->2->2->1->2->3
Output: No
Explanation: List 1 is not present in List 2.
The idea is to use a nested loop approach where we consider each node in the second list as a potential starting point for finding the first list. For each such starting point, we try to match the sequences of both lists, advancing through them simultaneously, and if the entire first list can be traversed while matching values with a consecutive portion of the second list, then the first list is indeed a sub list of the second.
Yes
The idea is to convert both linked lists into arrays and then apply the Knuth-Morris-Pratt (KMP) string matching algorithm to efficiently determine if the first list exists as a subsequence within the second list.
Step by step approach:
Yes