Open In App

Longest Common Prefix using Linked List

Last Updated : 23 Mar, 2023
Improve
Improve
Like Article
Like
Save
Share
Report

Given a set of strings, find the longest common prefix. 

Examples:

Input  : {“geeksforgeeks”, “geeks”, “geek”, “geezer”}
Output : "gee"

Input  : {"apple", "ape", "april"}
Output : "ap"

Previous Approaches: Word by Word Matching, Character by Character Matching, Divide and Conquer, Binary Search, Using Trie Data Structure

Below is an algorithm to solve above problem using Linked List.

  • Create a linked list using the characters of the first string as the data in the linked list.
  • Then one by one using all the remaining strings, iterate over the linked list deleting all the nodes after the point where the string gets exhausted or linked list gets exhausted or the characters do not match.
  • The remaining data in linked list is the required longest common prefix.

Below is the implementation in C++ 

C++




// C++ Program to find the longest common prefix
// in an array of strings
#include <bits/stdc++.h>
using namespace std;
 
// Structure for a node in the linked list
struct Node {
    char data;
    Node* next;
};
 
// Function to print the data in the linked list
// Remaining nodes represent the longest common prefix
void printLongestCommonPrefix(Node* head)
{
    // If the linked list is empty there is
    // no common prefix
    if (head == NULL) {
        cout << "There is no common prefix\n";
        return;
    }
 
    // Printing the longest common prefix
    cout << "The longest common prefix is ";
    while (head != NULL) {
        cout << head->data;
        head = head->next;
    }
}
 
// Function that creates a linked list of characters
// for the first word in the array of strings
void Initialise(Node** head, string str)
{
    // We calculate the length of the string
    // as we will insert from the last to the
    // first character
    int l = str.length();
 
    // Inserting all the nodes with the characters
    // using insert at the beginning technique
    for (int i = l - 1; i >= 0; i--) {
        Node* temp = new Node;
        temp->data = str[i];
        temp->next = *head;
        *head = temp;
    }
 
    // Since we have passed the address of the
    // head node it is not required to return
    // anything
}
 
// Function to delete all the nodes
// from the unmatched node till the end of the
// linked list
void deleteNodes(Node* head)
{
    // temp is used to facilitate the deletion of nodes
    Node* current = head;
    Node* next;
    while (current != NULL) {
        next = current->next;
        free(current);
        current = next;
    }
}
 
// Function that compares the character of the string with
// the nodes of the linked list and deletes all nodes after
// the characters that do not match
void longestCommonPrefix(Node** head, string str)
{
    int i = 0;
 
    // Use the pointer to the previous node to
    // delete the link between the unmatched node
    // and its prev node
    Node* temp = *head;
    Node* prev = *head;
    while (temp != NULL) {
 
        // If the current string finishes or if the
        // the characters in the linked list do not match
        // with the character at the corresponding position
        // delete all the nodes after that.
        if (str[i] == '\0' || temp->data != str[i]) {
 
            // If the first node does not match then there
            // is no common prefix
            if (temp == *head) {
                free(temp);
                *head = NULL;
            }
 
            // Delete all the nodes starting from the
            // unmatched node
            else {
                prev->next = NULL;
                deleteNodes(temp);
            }
            break;
        }
 
        // If the character matches, move to next
        // node and store the address of the current
        // node in prev
        prev = temp;
        temp = temp->next;
        i++;
    }
}
 
int main()
{
    string arr[] = { "geeksforgeeks", "geeks", "geek", "geezer",
                    "geekathon" };
    int n = sizeof(arr) / sizeof(arr[0]);
 
    struct Node* head = NULL;
 
    // A linked list is created with all the characters
    // of the first string
    Initialise(&head, arr[0]);
 
    // Process all the remaining strings to find the
    // longest common prefix
    for (int i = 1; i < n; i++)
        longestCommonPrefix(&head, arr[i]);
 
    printLongestCommonPrefix(head);
}


Java




// Java Program to find the longest common prefix
// in an array of strings
import java.util.Arrays;
 
public class Main {
     
    // Structure for a node in the linked list
    static class Node {
        char data;
        Node next;
    }
 
    // Function to print the data in the linked list
    // Remaining nodes represent the longest common prefix
    static void printLongestCommonPrefix(Node head)
    {
        // If the linked list is empty there is
        // no common prefix
        if (head == null) {
            System.out.println("There is no common prefix");
            return;
        }
 
        // Printing the longest common prefix
        System.out.print("The longest common prefix is ");
        while (head != null) {
            System.out.print(head.data);
            head = head.next;
        }
        System.out.println();
    }
 
    // Function that creates a linked list of characters
    // for the first word in the array of strings
    static void initialise(Node[] head, String str)
    {
        // we calculate the length of the string
        // as we will insert from the last to the
        // first character
        int l = str.length();
 
        // inserting all the nodes with the characters
        // using insert at the beginning technique
        for (int i = l - 1; i >= 0; i--) {
            Node temp = new Node();
            temp.data = str.charAt(i);
            temp.next = head[0];
            head[0] = temp;
        }
    }
 
    // Function to delete all the nodes
    // from the unmatched node till the end of the
    // linked list
    static void deleteNodes(Node head)
    {
        // temp is used to facilitate the deletion of nodes
        Node current = head;
        Node next;
        while (current != null) {
            next = current.next;
            current = null;
            current = next;
        }
    }
 
    // Function that compares the character of the string with
    // the nodes of the linked list and deletes all nodes after
    // the characters that do not match
    static void longestCommonPrefix(Node[] head, String str)
    {
        int i = 0;
 
        // Use the pointer to the previous node to
        // delete the link between the unmatched node
        // and its prev node
        Node temp = head[0];
        Node prev = head[0];
        while (temp != null) {
 
            // If the current string finishes or if the
            // the characters in the linked list do not match
            // with the character at the corresponding position
            // delete all the nodes after that.
            if (i == str.length() || temp.data != str.charAt(i)) {
 
                // If the first node does not match then there
                // is no common prefix
                if (temp == head[0]) {
                    head[0] = null;
                }
 
                // Delete all the nodes starting from the
                // unmatched node
                else {
                    prev.next = null;
                    deleteNodes(temp);
                }
                break;
            }
 
            // If the character matches, move to next
            // node and store the address of the current
            // node in prev
            prev = temp;
            temp = temp.next;
            i++;
        }
    }
 
    public static void main(String[] args)
    {
        String[] arr = { "geeksforgeeks", "geeks", "geek", "geezer", "geekathon" };
        int n = arr.length;
 
        Node[] head = new Node[1];
 
        // A linked list is created with all the characters
        // of the first string
        initialise(head, arr[0]);
 
        // Process all the remaining strings to find the
        // longest common prefix
        for (int i = 1; i < n; i++) {
            longestCommonPrefix(head, arr[i]);
        }
 
        printLongestCommonPrefix(head[0]);
    }
}


Python3




# Python Program to find the longest common prefix
# in an array of strings
 
# Class for a node in the linked list
class Node:
    def __init__(self, data):
        self.data = data
        self.next = None
 
# Function to print the data in the linked list
# Remaining nodes represent the longest common prefix
def printLongestCommonPrefix(head):
    # If the linked list is empty there is
    # no common prefix
    if head is None:
        print("There is no common prefix")
        return
 
    # Printing the longest common prefix
    print("The longest common prefix is ", end='')
    while head is not None:
        print(head.data, end='')
        head = head.next
    print()
 
# Function that creates a linked list of characters
# for the first word in the array of strings
def Initialise(head, string):
    # We calculate the length of the string
    # as we will insert from the last to the
    # first character
    l = len(string)
 
    # Inserting all the nodes with the characters
    # using insert at the beginning technique
    for i in range(l-1, -1, -1):
        temp = Node(string[i])
        temp.next = head[0]
        head[0] = temp
 
# Function to delete all the nodes
# from the unmatched node till the end of the
# linked list
def deleteNodes(head):
    # temp is used to facilitate the deletion of nodes
    current = head
    while current is not None:
        next = current.next
        del current
        current = next
 
# Function that compares the character of the string with
# the nodes of the linked list and deletes all nodes after
# the characters that do not match
def longestCommonPrefix(head, string):
    i = 0
 
    # Use the pointer to the previous node to
    # delete the link between the unmatched node
    # and its prev node
    temp = head[0]
    prev = head[0]
    while temp is not None:
 
        # If the current string finishes or if the
        # the characters in the linked list do not match
        # with the character at the corresponding position
        # delete all the nodes after that.
        if i == len(string) or temp.data != string[i]:
 
            # If the first node does not match then there
            # is no common prefix
            if temp == head[0]:
                del temp
                head[0] = None
 
            # Delete all the nodes starting from the
            # unmatched node
            else:
                prev.next = None
                deleteNodes(temp)
            break
 
        # If the character matches, move to next
        # node and store the address of the current
        # node in prev
        prev = temp
        temp = temp.next
        i += 1
 
if __name__ == "__main__":
    arr = ["geeksforgeeks", "geeks", "geek", "geezer", "geekathon"]
    n = len(arr)
 
    head = [None]
 
    # A linked list is created with all the characters
    # of the first string
    Initialise(head, arr[0])
 
    # Process all the remaining strings to find the
    # longest common prefix
    for i in range(1, n):
        longestCommonPrefix(head, arr[i])
 
    printLongestCommonPrefix(head[0])
 
# This code is contributed by codebraxnzt


C#




using System;
 
// Structure for a node in the linked list
public class Node {
    public char data;
    public Node next;
}
 
public class LongestCommon_Prefix {
    // Function to print the data in the linked list
    // Remaining nodes represent the longest common prefix
    static void PrintLongestCommonPrefix(Node head) {
        // If the linked list is empty there is
        // no common prefix
        if (head == null) {
            Console.WriteLine("There is no common prefix");
            return;
        }
 
        // Printing the longest common prefix
        Console.Write("The longest common prefix is ");
        while (head != null) {
            Console.Write(head.data);
            head = head.next;
        }
        Console.WriteLine();
    }
 
    // Function that creates a linked list of characters
    // for the first word in the array of strings
    static void Initialise(ref Node head, string str) {
        // We calculate the length of the string
        // as we will insert from the last to the
        // first character
        int l = str.Length;
 
        // Inserting all the nodes with the characters
        // using insert at the beginning technique
        for (int i = l - 1; i >= 0; i--) {
            Node temp = new Node();
            temp.data = str[i];
            temp.next = head;
            head = temp;
        }
    }
 
    // Function to delete all the nodes
    // from the unmatched node till the end of the
    // linked list
    static void DeleteNodes(Node head) {
        // temp is used to facilitate the deletion of nodes
        Node current = head;
        Node next;
        while (current != null) {
            next = current.next;
            current = null;
            current = next;
        }
    }
 
    // Function that compares the character of the string with
    // the nodes of the linked list and deletes all nodes after
    // the characters that do not match
    static void LongestCommonPrefix(ref Node head, string str) {
        int i = 0;
 
        // Use the pointer to the previous node to
        // delete the link between the unmatched node
        // and its prev node
        Node temp = head;
        Node prev = head;
        while (temp != null) {
 
            // If the current string finishes or if the
            // the characters in the linked list do not match
            // with the character at the corresponding position
            // delete all the nodes after that.
            if (i == str.Length || temp.data != str[i]) {
 
                // If the first node does not match then there
                // is no common prefix
                if (temp == head) {
                    head = null;
                }
 
                // Delete all the nodes starting from the
                // unmatched node
                else {
                    prev.next = null;
                    DeleteNodes(temp);
                }
                break;
            }
 
            // If the character matches, move to next
            // node and store the address of the current
            // node in prev
            prev = temp;
            temp = temp.next;
            i++;
        }
    }
 
    static void Main() {
        string[] arr = { "geeksforgeeks", "geeks", "geek", "geezer", "geekathon" };
        int n = arr.Length;
 
        Node head = null;
 
        // A linked list is created with all the characters
        // of the first string
        Initialise(ref head, arr[0]);
 
        // Process all the remaining strings
        for (int i = 1; i < n; i++)
            LongestCommonPrefix(ref head, arr[i]);
        PrintLongestCommonPrefix(head);
    }
}


Javascript




// JavaScript Program to find the longest common prefix
// in an array of strings
 
// Class for a node in the linked list
class Node {
  constructor(data) {
    this.data = data;
    this.next = null;
  }
}
 
// Function to print the data in the linked list
// Remaining nodes represent the longest common prefix
function printLongestCommonPrefix(head) {
  // If the linked list is empty there is
  // no common prefix
  if (head == null) {
    console.log("There is no common prefix");
    return;
  }
ans="";
  // Printing the longest common prefix
  while (head != null) {
    ans = ans + head.data;
    head = head.next;
  }
  console.log("The longest common prefix is " + ans);
}
 
// Function that creates a linked list of characters
// for the first word in the array of strings
function Initialise(head, string) {
  // We calculate the length of the string
  // as we will insert from the last to the
  // first character
  let l = string.length;
 
  // Inserting all the nodes with the characters
  // using insert at the beginning technique
  for (let i = l-1; i >= 0; i--) {
    let temp = new Node(string[i]);
    temp.next = head[0];
    head[0] = temp;
  }
}
 
// Function to delete all the nodes
// from the unmatched node till the end of the
// linked list
function deleteNodes(head) {
  // temp is used to facilitate the deletion of nodes
  let current = head;
  while (current != null) {
    let next = current.next;
    delete current;
    current = next;
  }
}
 
// Function that compares the character of the string with
// the nodes of the linked list and deletes all nodes after
// the characters that do not match
function longestCommonPrefix(head, string) {
  let i = 0;
 
  // Use the pointer to the previous node to
  // delete the link between the unmatched node
  // and its prev node
  let temp = head[0];
  let prev = head[0];
  while (temp != null) {
 
    // If the current string finishes or if the
    // the characters in the linked list do not match
    // with the character at the corresponding position
    // delete all the nodes after that.
    if (i == string.length || temp.data != string[i]) {
 
      // If the first node does not match then there
      // is no common prefix
      if (temp == head[0]) {
        delete temp;
        head[0] = null;
      }
 
      // Delete all the nodes starting from the
      // unmatched node
      else {
        prev.next = null;
        deleteNodes(temp);
      }
      break;
    }
 
    // If the character matches, move to next
    // node and store the address of the current
    // node in prev
    prev = temp;
    temp = temp.next;
    i += 1;
  }
}
 
 
  let arr = ["geeksforgeeks", "geeks", "geek", "geezer", "geekathon"];
  let n = arr.length;
 
  let head = [null];
 
  // A linked list is created with all the characters
  // of the first string
  Initialise(head, arr[0]);
 
  // Process all the remaining strings to find the
  // longest common prefix
  for (let i = 1; i < n; i++) {
    longestCommonPrefix(head, arr[i]);
  }
 
  printLongestCommonPrefix(head[0]);


Output

The longest common prefix is gee


Like Article
Suggest improvement
Previous
Next
Share your thoughts in the comments

Similar Reads