VOOZH about

URL: https://www.geeksforgeeks.org/dsa/sublist-search-search-a-linked-list-in-another-list/

⇱ Sublist Search (Search a linked list in another list) - GeeksforGeeks


  • Courses
  • Tutorials
  • Interview Prep

Sublist Search (Search a linked list in another list)

Last Updated : 23 Jul, 2025

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 -> 20

Input: list1 = 1->2, list2 = 1->2->1->2->3->4
Output: Yes
Explanation: 1 -> 2 -> 1 -> 2 -> 3 -> 4

Input: list1 = 1->2->3->4, list2 = 1->2->2->1->2->3
Output: No
Explanation: List 1 is not present in List 2.

[Naive Approach] Using Iterative Method - O(n * m) time and O(1) space

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.


Output
Yes

[Expected Approach] Using KMP Algorithm - O(n + m) time and O(n + m) space

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:

  1. Convert both linked lists to arrays (pattern from list1, text from list2)
  2. Build the LPS (Longest Prefix Suffix) array for the pattern to track partial matches
  3. Perform the KMP search algorithm on the text and pattern arrays
  4. Return true if the pattern is found in the text, false otherwise

Output
Yes
Comment