Monday, December 30, 2024
Google search engine
HomeData Modelling & AICount occurrences of one linked list in another Linked List

Count occurrences of one linked list in another Linked List

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


Output

Occurrences 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


Output

Occurrences 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:

Feeling lost in the world of random DSA topics, wasting time without progress? It’s time for a change! Join our DSA course, where we’ll guide you on an exciting journey to master DSA efficiently and on schedule.
Ready to dive in? Explore our Free Demo Content and join our DSA course, trusted by over 100,000 neveropen!

Last Updated :
15 Sep, 2023
Like Article
Save Article


Previous

<!–

8 Min Read | Java

–>


Next


<!–

8 Min Read | Java

–>

RELATED ARTICLES

Most Popular

Recent Comments