Count occurrences of one linked list in another Linked List
Last Updated :
15 Sep, 2023
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
DSA Tutorial - Learn Data Structures and Algorithms
DSA (Data Structures and Algorithms) is the study of organizing data efficiently using data structures like arrays, stacks, and trees, paired with step-by-step procedures (or algorithms) to solve problems effectively. Data structures manage how data is stored and accessed, while algorithms focus on
7 min read
Quick Sort
QuickSort is a sorting algorithm based on the Divide and Conquer that picks an element as a pivot and partitions the given array around the picked pivot by placing the pivot in its correct position in the sorted array. It works on the principle of divide and conquer, breaking down the problem into s
12 min read
Merge Sort - Data Structure and Algorithms Tutorials
Merge sort is a popular sorting algorithm known for its efficiency and stability. It follows the divide-and-conquer approach. It works by recursively dividing the input array into two halves, recursively sorting the two halves and finally merging them back together to obtain the sorted array. Merge
14 min read
Bubble Sort Algorithm
Bubble Sort is the simplest sorting algorithm that works by repeatedly swapping the adjacent elements if they are in the wrong order. This algorithm is not suitable for large data sets as its average and worst-case time complexity are quite high.We sort the array using multiple passes. After the fir
8 min read
Breadth First Search or BFS for a Graph
Given a undirected graph represented by an adjacency list adj, where each adj[i] represents the list of vertices connected to vertex i. Perform a Breadth First Search (BFS) traversal starting from vertex 0, visiting vertices from left to right according to the adjacency list, and return a list conta
15+ min read
Data Structures Tutorial
Data structures are the fundamental building blocks of computer programming. They define how data is organized, stored, and manipulated within a program. Understanding data structures is very important for developing efficient and effective algorithms. What is Data Structure?A data structure is a st
2 min read
Binary Search Algorithm - Iterative and Recursive Implementation
Binary Search Algorithm is a searching algorithm used in a sorted array by repeatedly dividing the search interval in half. The idea of binary search is to use the information that the array is sorted and reduce the time complexity to O(log N). Binary Search AlgorithmConditions to apply Binary Searc
15 min read
Insertion Sort Algorithm
Insertion sort is a simple sorting algorithm that works by iteratively inserting each element of an unsorted list into its correct position in a sorted portion of the list. It is like sorting playing cards in your hands. You split the cards into two groups: the sorted cards and the unsorted cards. T
9 min read
Dijkstra's Algorithm to find Shortest Paths from a Source to all
Given a weighted undirected graph represented as an edge list and a source vertex src, find the shortest path distances from the source vertex to all other vertices in the graph. The graph contains V vertices, numbered from 0 to V - 1.Note: The given graph does not contain any negative edge. Example
12 min read
Selection Sort
Selection Sort is a comparison-based sorting algorithm. It sorts an array by repeatedly selecting the smallest (or largest) element from the unsorted portion and swapping it with the first unsorted element. This process continues until the entire array is sorted.First we find the smallest element an
8 min read