Count occurrences of one linked list in another Linked List
Last Updated :
23 Jul, 2025
Given two linked lists head1 and head2, the task is to find occurrences of head2 in head1.
Examples:
Input: Head1 = 1->2->3->2->4->5->2->4, Head2 = 2->4
Output: Occurrences of head2 in head1: 2
Input: Head1 = 3->4->1->5->2, Head2 = 3->4
Output: Occurrences of Head2 in Head1: 1
Approach 1: To solve the problem using Sliding Window Approach:
The idea is to use sliding window approach. We will traverse the first linked list head1, and at each node, we will check if the current node is equal to the first node of head2. If it is, then we will start a new traversal of both linked lists from this node, and check if all nodes in head2 match the nodes in head1 starting from this node. If they match, we will count it as an occurrence.
Below are the steps for the above approach:
- Initialize a variable count = zero.
- Traverse the first linked list head1 using a while loop that runs until head1 is NULL. At each node in head1,
- Initialize two pointers p1 and p2 to the current node in head1 and the head of head2, respectively.
- Run a nested while loop that traverses both linked lists starting from p1 and p2, and checks if the values of the nodes are equal. If they are not, the loop breaks and we move on to the next node in head1. If they are equal and we reach the end of head2, it means that we have found a match, and we increment the counter variable count.
- Update p1 to point to the next node in head1, and update p2 to point to the head of head2.
- After traversing the entire first linked list, return the final value of the counter variable count.
Below is the code for the above approach:
C++
// C++ code for the above approach:
#include <bits/stdc++.h>
using namespace std;
struct Node {
int val;
Node* next;
Node(int x)
: val(x), next(NULL)
{
}
};
// Function to count occurences
int countOccurrences(Node* head1, Node* head2)
{
int count = 0;
while (head1 != NULL) {
Node* p1 = head1;
Node* p2 = head2;
while (p1 != NULL && p2 != NULL
&& p1->val == p2->val) {
p1 = p1->next;
p2 = p2->next;
}
if (p2 == NULL) {
count++;
}
head1 = head1->next;
}
return count;
}
// Drivers code
int main()
{
// Initialize the first linked list
Node* head1 = new Node(1);
head1->next = new Node(2);
head1->next->next = new Node(3);
head1->next->next->next = new Node(2);
head1->next->next->next->next = new Node(4);
head1->next->next->next->next->next = new Node(5);
head1->next->next->next->next->next->next = new Node(2);
head1->next->next->next->next->next->next->next
= new Node(4);
// Initialize the second linked list
Node* head2 = new Node(2);
head2->next = new Node(4);
// Count the occurrences of head2 in head1
int count = countOccurrences(head1, head2);
// Output the result
cout << "Occurrences of head2 in head1: " << count
<< endl;
return 0;
}
Java
// Java code implementation
class Node {
int val;
Node next;
public Node(int x) {
val = x;
next = null;
}
}
public class Main {
// Function to count occurrences
static int countOccurrences(Node head1, Node head2) {
int count = 0;
while (head1 != null) {
Node p1 = head1;
Node p2 = head2;
while (p1 != null && p2 != null && p1.val == p2.val) {
p1 = p1.next;
p2 = p2.next;
}
if (p2 == null) {
count++;
}
head1 = head1.next;
}
return count;
}
// Drivers code
public static void main(String[] args) {
// Initialize the first linked list
Node head1 = new Node(1);
head1.next = new Node(2);
head1.next.next = new Node(3);
head1.next.next.next = new Node(2);
head1.next.next.next.next = new Node(4);
head1.next.next.next.next.next = new Node(5);
head1.next.next.next.next.next.next = new Node(2);
head1.next.next.next.next.next.next.next = new Node(4);
// Initialize the second linked list
Node head2 = new Node(2);
head2.next = new Node(4);
// Count the occurrences of head2 in head1
int count = countOccurrences(head1, head2);
// Output the result
System.out.println("Occurrences of head2 in head1: " + count);
}
}
Python3
# Python code for the above approach
class Node:
def __init__(self, x):
self.val = x
self.next = None
# Function to count occurrences
def countOccurrences(head1, head2):
count = 0
while head1 != None:
p1 = head1
p2 = head2
while p1 != None and p2 != None and p1.val == p2.val:
p1 = p1.next
p2 = p2.next
if p2 == None:
count += 1
head1 = head1.next
return count
# Driver code
if __name__ == '__main__':
# Initialize the first linked list
head1 = Node(1)
head1.next = Node(2)
head1.next.next = Node(3)
head1.next.next.next = Node(2)
head1.next.next.next.next = Node(4)
head1.next.next.next.next.next = Node(5)
head1.next.next.next.next.next.next = Node(2)
head1.next.next.next.next.next.next.next = Node(4)
# Initialize the second linked list
head2 = Node(2)
head2.next = Node(4)
# Count the occurrences of head2 in head1
count = countOccurrences(head1, head2)
# Output the result
print("Occurrences of head2 in head1:", count)
C#
using System;
class Node
{
public int val;
public Node next;
public Node(int x)
{
val = x;
next = null;
}
}
class Program
{
// Function to count occurrences
static int CountOccurrences(Node head1, Node head2)
{
int count = 0;
while (head1 != null)
{
Node p1 = head1;
Node p2 = head2;
while (p1 != null && p2 != null && p1.val == p2.val)
{
p1 = p1.next;
p2 = p2.next;
}
if (p2 == null)
{
count++;
}
head1 = head1.next;
}
return count;
}
// Driver code
static void Main()
{
// Initialize the first linked list
Node head1 = new Node(1);
head1.next = new Node(2);
head1.next.next = new Node(3);
head1.next.next.next = new Node(2);
head1.next.next.next.next = new Node(4);
head1.next.next.next.next.next = new Node(5);
head1.next.next.next.next.next.next = new Node(2);
head1.next.next.next.next.next.next.next = new Node(4);
// Initialize the second linked list
Node head2 = new Node(2);
head2.next = new Node(4);
// Count the occurrences of head2 in head1
int count = CountOccurrences(head1, head2);
// Output the result
Console.WriteLine("Occurrences of head2 in head1: " + count);
}
}
JavaScript
// Javascript code for the above approach:
class Node {
constructor(val) {
this.val = val;
this.next = null;
}
}
// Function to count occurrences
function countOccurrences(head1, head2) {
let count = 0;
while (head1 !== null) {
let p1 = head1;
let p2 = head2;
while (p1 !== null && p2 !== null && p1.val === p2.val) {
p1 = p1.next;
p2 = p2.next;
}
if (p2 === null) {
count++;
}
head1 = head1.next;
}
return count;
}
// Drivers code
// Initialize the first linked list
const head1 = new Node(1);
head1.next = new Node(2);
head1.next.next = new Node(3);
head1.next.next.next = new Node(2);
head1.next.next.next.next = new Node(4);
head1.next.next.next.next.next = new Node(5);
head1.next.next.next.next.next.next = new Node(2);
head1.next.next.next.next.next.next.next = new Node(4);
// Initialize the second linked list
const head2 = new Node(2);
head2.next = new Node(4);
// Count the occurrences of head2 in head1
const count = countOccurrences(head1, head2);
// Output the result
console.log("Occurrences of head2 in head1:", count);
// this code is contributed by uttamdp_10
OutputOccurrences of head2 in head1: 2
Time Complexity: O(m*n), where m and n are the lengths of the two linked lists
Auxiliary Space: O(1)
Approach 2: To solve the problem using Knuth-Morris-Pratt (KMP) algorithm
The basic idea of using a string matching algorithm is to treat the linked lists as strings and search for the second linked list within the first linked list as a substring.
Below are the steps for the above approach:
- Convert the linked lists to strings by concatenating their values in order.
- Use the KMP algorithm to search for the second string within the first string. The KMP algorithm searches for the occurrence of a pattern within a text by using a preprocessed table that is based on the pattern.
- Initialize two pointers p1 and p2 to the head of the first linked list and the second linked list, respectively.
- Traverse the first linked list using p1 and update p2 based on the preprocessed table. If we reach the end of the second linked list, it means that we have found a match, and we can increment the count.
- After traversing the entire first linked list, return the final value of the count.
Below is the code for the above approach:
C++
// C++ code for the above approach:
#include <bits/stdc++.h>
using namespace std;
struct Node {
int val;
Node* next;
Node(int x)
: val(x), next(NULL)
{
}
};
// Function to concatenate the values
// of a linked list into a string
string concatenateList(Node* head)
{
string result = "";
Node* current = head;
while (current != NULL) {
result += to_string(current->val);
current = current->next;
}
return result;
}
// Function to compute the prefix table
// for the KMP algorithm
void computePrefixTable(string pattern, int* prefixTable)
{
int m = pattern.length();
int j = 0;
prefixTable[0] = 0;
for (int i = 1; i < m; i++) {
while (j > 0 && pattern[j] != pattern[i]) {
j = prefixTable[j - 1];
}
if (pattern[j] == pattern[i]) {
j++;
}
prefixTable[i] = j;
}
}
// Function to count the occurrences of a
// second linked list within a
// first linked list
int countOccurrences(Node* head1, Node* head2)
{
string text = concatenateList(head1);
string pattern = concatenateList(head2);
int n = text.length();
int m = pattern.length();
if (m == 0) {
return 0;
}
int prefixTable[m];
computePrefixTable(pattern, prefixTable);
int count = 0;
int i = 0;
int j = 0;
while (i < n) {
if (text[i] == pattern[j]) {
i++;
j++;
if (j == m) {
count++;
j = prefixTable[j - 1];
}
}
else if (j > 0) {
j = prefixTable[j - 1];
}
else {
i++;
}
}
return count;
}
// Drivers code
int main()
{
// Initialize the first linked list
Node* head1 = new Node(1);
head1->next = new Node(2);
head1->next->next = new Node(3);
head1->next->next->next = new Node(2);
head1->next->next->next->next = new Node(4);
head1->next->next->next->next->next = new Node(5);
head1->next->next->next->next->next->next = new Node(2);
head1->next->next->next->next->next->next->next
= new Node(4);
// Initialize the second linked list
Node* head2 = new Node(2);
head2->next = new Node(4);
// Function Call
int result = countOccurrences(head1, head2);
cout << "Occurrences of head2 in head1: " << result
<< endl;
return 0;
}
Java
import java.io.*;
import java.util.*;
class Node {
int val;
Node next;
Node(int x) {
val = x;
next = null;
}
}
public class GFG {
// Function to concatenate the values
// of a linked list into string
public static String concatenateList(Node head) {
StringBuilder result = new StringBuilder();
Node current = head;
while (current != null) {
result.append(current.val);
current = current.next;
}
return result.toString();
}
// Function to compute the prefix table
// for the KMP algorithm
public static void computePrefixTable(String pattern, int[] prefixTable) {
int m = pattern.length();
int j = 0;
prefixTable[0] = 0;
for (int i = 1; i < m; i++) {
while (j > 0 && pattern.charAt(j) != pattern.charAt(i)) {
j = prefixTable[j - 1];
}
if (pattern.charAt(j) == pattern.charAt(i)) {
j++;
}
prefixTable[i] = j;
}
}
// Function to count the occurrences of
// second linked list within a
// first linked list
public static int countOccurrences(Node head1, Node head2) {
String text = concatenateList(head1);
String pattern = concatenateList(head2);
int n = text.length();
int m = pattern.length();
if (m == 0) {
return 0;
}
int[] prefixTable = new int[m];
computePrefixTable(pattern, prefixTable);
int count = 0;
int i = 0;
int j = 0;
while (i < n) {
if (text.charAt(i) == pattern.charAt(j)) {
i++;
j++;
if (j == m) {
count++;
j = prefixTable[j - 1];
}
} else if (j > 0) {
j = prefixTable[j - 1];
} else {
i++;
}
}
return count;
}
// Drivers code
public static void main(String[] args) {
// Initialize the first linked list
Node head1 = new Node(1);
head1.next = new Node(2);
head1.next.next = new Node(3);
head1.next.next.next = new Node(2);
head1.next.next.next.next = new Node(4);
head1.next.next.next.next.next = new Node(5);
head1.next.next.next.next.next.next = new Node(2);
head1.next.next.next.next.next.next.next = new Node(4);
// Initialize the second linked list
Node head2 = new Node(2);
head2.next = new Node(4);
// Function Call
int result = countOccurrences(head1, head2);
System.out.println("Occurrences of head2 in head1: " + result);
}
}
Python3
# Python3 code for the above approach
class Node:
def __init__(self, x):
self.val = x
self.next = None
# Function to concatenate the values
# of a linked list into a string
def concatenateList(head):
result = ""
current = head
while current is not None:
result += str(current.val)
current = current.next
return result
# Function to compute the prefix table
# for the KMP algorithm
def computePrefixTable(pattern, prefixTable):
m = len(pattern)
j = 0
prefixTable[0] = 0
for i in range(1, m):
while j > 0 and pattern[j] != pattern[i]:
j = prefixTable[j - 1]
if pattern[j] == pattern[i]:
j += 1
prefixTable[i] = j
# Function to count the occurrences of a
# second linked list within a
# first linked list
def countOccurrences(head1, head2):
text = concatenateList(head1)
pattern = concatenateList(head2)
n = len(text)
m = len(pattern)
if m == 0:
return 0
prefixTable = [0] * m
computePrefixTable(pattern, prefixTable)
count = 0
i = 0
j = 0
while i < n:
if text[i] == pattern[j]:
i += 1
j += 1
if j == m:
count += 1
j = prefixTable[j - 1]
elif j > 0:
j = prefixTable[j - 1]
else:
i += 1
return count
# Drivers code
if __name__ == "__main__":
# Initialize the first linked list
head1 = Node(1)
head1.next = Node(2)
head1.next.next = Node(3)
head1.next.next.next = Node(2)
head1.next.next.next.next = Node(4)
head1.next.next.next.next.next = Node(5)
head1.next.next.next.next.next.next = Node(2)
head1.next.next.next.next.next.next.next = Node(4)
# Initialize the second linked list
head2 = Node(2)
head2.next = Node(4)
# Function Call
result = countOccurrences(head1, head2)
print("Occurrences of head2 in head1:", result)
C#
// C# code implementation of above approach
using System;
public class Node {
public int val;
public Node next;
public Node(int x) {
val = x;
next = null;
}
}
public class LinkedListOccurrence {
// Function to concatenate the values
// of a linked list into a string
public static string ConcatenateList(Node head) {
string result = "";
Node current = head;
while (current != null) {
result += current.val.ToString();
current = current.next;
}
return result;
}
// Function to compute the prefix table
// for the KMP algorithm
public static void ComputePrefixTable(string pattern, int[] prefixTable) {
int m = pattern.Length;
int j = 0;
prefixTable[0] = 0;
for (int i = 1; i < m; i++) {
while (j > 0 && pattern[j] != pattern[i]) {
j = prefixTable[j - 1];
}
if (pattern[j] == pattern[i]) {
j++;
}
prefixTable[i] = j;
}
}
// Function to count the occurrences of a
// second linked list within a
// first linked list
public static int CountOccurrences(Node head1, Node head2) {
string text = ConcatenateList(head1);
string pattern = ConcatenateList(head2);
int n = text.Length;
int m = pattern.Length;
if (m == 0) {
return 0;
}
int[] prefixTable = new int[m];
ComputePrefixTable(pattern, prefixTable);
int count = 0;
int i = 0;
int j = 0;
while (i < n) {
if (text[i] == pattern[j]) {
i++;
j++;
if (j == m) {
count++;
j = prefixTable[j - 1];
}
}
else if (j > 0) {
j = prefixTable[j - 1];
}
else {
i++;
}
}
return count;
}
// Drivers code
public static void Main() {
// Initialize the first linked list
Node head1 = new Node(1);
head1.next = new Node(2);
head1.next.next = new Node(3);
head1.next.next.next = new Node(2);
head1.next.next.next.next = new Node(4);
head1.next.next.next.next.next = new Node(5);
head1.next.next.next.next.next.next = new Node(2);
head1.next.next.next.next.next.next.next = new Node(4);
// Initialize the second linked list
Node head2 = new Node(2);
head2.next = new Node(4);
// Function Call
int result = CountOccurrences(head1, head2);
Console.WriteLine("Occurrences of head2 in head1: " + result);
}
}
JavaScript
// Javascript code for above approach :
class Node {
constructor(val) {
this.val = val;
this.next = null;
}
}
// Function to concatenate the values
// of a linked list into a string
function concatenateList(head) {
let result = "";
let current = head;
while (current !== null) {
result += current.val.toString();
current = current.next;
}
return result;
}
// Function to compute the prefix table
// for the KMP algorithm
function computePrefixTable(pattern) {
const m = pattern.length;
const prefixTable = new Array(m).fill(0);
let j = 0;
for (let i = 1; i < m; i++) {
while (j > 0 && pattern[j] !== pattern[i]) {
j = prefixTable[j - 1];
}
if (pattern[j] === pattern[i]) {
j++;
}
prefixTable[i] = j;
}
return prefixTable;
}
// Function to count the occurrences of a
// second linked list within a
// first linked list
function countOccurrences(head1, head2) {
const text = concatenateList(head1);
const pattern = concatenateList(head2);
const n = text.length;
const m = pattern.length;
if (m === 0) {
return 0;
}
const prefixTable = computePrefixTable(pattern);
let count = 0;
let i = 0;
let j = 0;
while (i < n) {
if (text[i] === pattern[j]) {
i++;
j++;
if (j === m) {
count++;
j = prefixTable[j - 1];
}
} else if (j > 0) {
j = prefixTable[j - 1];
} else {
i++;
}
}
return count;
}
// Driver's code
// Initialize the first linked list
const head1 = new Node(1);
head1.next = new Node(2);
head1.next.next = new Node(3);
head1.next.next.next = new Node(2);
head1.next.next.next.next = new Node(4);
head1.next.next.next.next.next = new Node(5);
head1.next.next.next.next.next.next = new Node(2);
head1.next.next.next.next.next.next.next = new Node(4);
// Initialize the second linked list
const head2 = new Node(2);
head2.next = new Node(4);
// Function Call
const result = countOccurrences(head1, head2);
console.log("Occurrences of head2 in head1:", result);
// this code is contributed by uttamdp_10
OutputOccurrences of head2 in head1: 2
Time Complexity: O(m+n), where m and n are the lengths of the two linked lists.
Auxiliary Space: O(m), where m is the length of the pattern (the second linked list).
Related articles:
Similar Reads
Basics & Prerequisites
Data Structures
Array Data StructureIn this article, we introduce array, implementation in different popular languages, its basic operations and commonly seen problems / interview questions. An array stores items (in case of C/C++ and Java Primitive Arrays) or their references (in case of Python, JS, Java Non-Primitive) at contiguous
3 min read
String in Data StructureA string is a sequence of characters. The following facts make string an interesting data structure.Small set of elements. Unlike normal array, strings typically have smaller set of items. For example, lowercase English alphabet has only 26 characters. ASCII has only 256 characters.Strings are immut
2 min read
Hashing in Data StructureHashing is a technique used in data structures that efficiently stores and retrieves data in a way that allows for quick access. Hashing involves mapping data to a specific index in a hash table (an array of items) using a hash function. It enables fast retrieval of information based on its key. The
2 min read
Linked List Data StructureA linked list is a fundamental data structure in computer science. It mainly allows efficient insertion and deletion operations compared to arrays. Like arrays, it is also used to implement other data structures like stack, queue and deque. Hereâs the comparison of Linked List vs Arrays Linked List:
2 min read
Stack Data StructureA Stack is a linear data structure that follows a particular order in which the operations are performed. The order may be LIFO(Last In First Out) or FILO(First In Last Out). LIFO implies that the element that is inserted last, comes out first and FILO implies that the element that is inserted first
2 min read
Queue Data StructureA Queue Data Structure is a fundamental concept in computer science used for storing and managing data in a specific order. It follows the principle of "First in, First out" (FIFO), where the first element added to the queue is the first one to be removed. It is used as a buffer in computer systems
2 min read
Tree Data StructureTree Data Structure is a non-linear data structure in which a collection of elements known as nodes are connected to each other via edges such that there exists exactly one path between any two nodes. Types of TreeBinary Tree : Every node has at most two childrenTernary Tree : Every node has at most
4 min read
Graph Data StructureGraph Data Structure is a collection of nodes connected by edges. It's used to represent relationships between different entities. If you are looking for topic-wise list of problems on different topics like DFS, BFS, Topological Sort, Shortest Path, etc., please refer to Graph Algorithms. Basics of
3 min read
Trie Data StructureThe Trie data structure is a tree-like structure used for storing a dynamic set of strings. It allows for efficient retrieval and storage of keys, making it highly effective in handling large datasets. Trie supports operations such as insertion, search, deletion of keys, and prefix searches. In this
15+ min read
Algorithms
Searching AlgorithmsSearching algorithms are essential tools in computer science used to locate specific items within a collection of data. In this tutorial, we are mainly going to focus upon searching in an array. When we search an item in an array, there are two most common algorithms used based on the type of input
2 min read
Sorting AlgorithmsA Sorting Algorithm is used to rearrange a given array or list of elements in an order. For example, a given array [10, 20, 5, 2] becomes [2, 5, 10, 20] after sorting in increasing order and becomes [20, 10, 5, 2] after sorting in decreasing order. There exist different sorting algorithms for differ
3 min read
Introduction to RecursionThe process in which a function calls itself directly or indirectly is called recursion and the corresponding function is called a recursive function. A recursive algorithm takes one step toward solution and then recursively call itself to further move. The algorithm stops once we reach the solution
14 min read
Greedy AlgorithmsGreedy algorithms are a class of algorithms that make locally optimal choices at each step with the hope of finding a global optimum solution. At every step of the algorithm, we make a choice that looks the best at the moment. To make the choice, we sometimes sort the array so that we can always get
3 min read
Graph AlgorithmsGraph is a non-linear data structure like tree data structure. The limitation of tree is, it can only represent hierarchical data. For situations where nodes or vertices are randomly connected with each other other, we use Graph. Example situations where we use graph data structure are, a social net
3 min read
Dynamic Programming or DPDynamic Programming is an algorithmic technique with the following properties.It is mainly an optimization over plain recursion. Wherever we see a recursive solution that has repeated calls for the same inputs, we can optimize it using Dynamic Programming. The idea is to simply store the results of
3 min read
Bitwise AlgorithmsBitwise algorithms in Data Structures and Algorithms (DSA) involve manipulating individual bits of binary representations of numbers to perform operations efficiently. These algorithms utilize bitwise operators like AND, OR, XOR, NOT, Left Shift, and Right Shift.BasicsIntroduction to Bitwise Algorit
4 min read
Advanced
Segment TreeSegment Tree is a data structure that allows efficient querying and updating of intervals or segments of an array. It is particularly useful for problems involving range queries, such as finding the sum, minimum, maximum, or any other operation over a specific range of elements in an array. The tree
3 min read
Pattern SearchingPattern searching algorithms are essential tools in computer science and data processing. These algorithms are designed to efficiently find a particular pattern within a larger set of data. Patten SearchingImportant Pattern Searching Algorithms:Naive String Matching : A Simple Algorithm that works i
2 min read
GeometryGeometry is a branch of mathematics that studies the properties, measurements, and relationships of points, lines, angles, surfaces, and solids. From basic lines and angles to complex structures, it helps us understand the world around us.Geometry for Students and BeginnersThis section covers key br
2 min read
Interview Preparation
Practice Problem