# Longest Common Prefix in Linked List

The longest common prefix problem is a well-known computer science problem that is frequently encountered when working with strings or lists. It entails determining the string or list element with the longest common prefix.

When it comes to linked lists, there are several approaches that can be taken. One common approach is to traverse the linked list and compare the characters of each node in the list until a mismatch is found. The longest common prefix up to the point of mismatch is considered.

A linear linked list can be defined as a collection of variable number of data items. An element of list must contain at least two fields, one for storing data and other for storing address of next element. The second field of list must be pointer type. Each such element is known as a node, thus a list can be defined as collection of nodes.

Some operations associated with linked list are −

• Creation

• Insertion

• Deletion

• Traversing

• Searching

• Concatenation

• Display

### Algorithm of the Longest Common Prefix in a Linked List

• Step 1 − Go through the linked list, comparing each node's characters, looking for mismatches or stopping when the list is at its end.

• Step 2 − In the event that a discrepancy is discovered before the conclusion of the list, the prefix up to the preceding node is regarded as the longest common prefix.

• Step 3 − The lengthiest common prefix is the one that spans the full list if no mismatch is discovered and the list's conclusion is reached.

The longest common prefix is returned as a string by the function longest common prefix in this implementation, which accepts the head of a linked list as input. In order to return an empty string, the function first determines whether the linked list is empty. If not, the prefix is initialized to the value of the head node and the list traversal begins at the second node. The function does a prefix-value comparison for each node, removing characters from the prefix until a mismatch is discovered. An empty string is returned by the function if the prefix ever becomes empty. The function finally delivers the last prefix as the longest common prefix.

### Syntax of Longest Common Prefix in Linked List

The syntax for the longest Common Prefix function, which finds the longest common prefix in a linked list of strings −

class Solution {
public:
string longestCommonPrefix(vector<string>& strs) {
int z = INT_MAX;
if(strs.size()==0) return "";
string c = strs[0];
for(int p=1; p<strs.size(); p++){
int q=0,r=0,result=0;
while(q<c.size() && r<strs[p].size()){
if(c[q] == strs[p][r]) result++;
else break;
q++; r++;
}
z = min(result,z);
}
return c.substr(0,z);
}
};


The structure for a node in the linked list in this case is called List Node, and it includes a string value and a pointer to the node after it. The function accepts a reference to the linked list's head as input and outputs a string that contains the linked list's longest common prefix.

Depending on the precise needs of the situation, the function may be implemented differently, but in general, iterating through the linked list and comparing the characters of each string until the largest common prefix is found is how it is done.

## Approaches to Follow

### Approach-1

In the above a code, the linked list is first examined to see if it is empty or not. If it is empty, since there is not a common prefix, we return an empty string.

Prefix is then initialized to list's first string. Then by starting with the second element, we go down in the list and compare each string with the prefix.

When there is a difference between the prefix and the current string we keep track of the index of first character that is at fault. Then the prefix to the substring up to that index is updated.

The longest common prefix, is finally returned. The output of the as mentioned before sample code will be longest common prefix: fl.

### Example-1

#include <iostream>
#include <string>
using namespace std;
struct Listnode {
string value;
Listnode* next;
Listnode(string x) : value(x), next(0) {}
};
return "";
}
while (current != nullptr) {
string str = current->value;
int i = 0;
while (i < prefix.length() && i < str.length() && prefix[i] == str[i]) {
i++;
}
prefix = prefix.substr(0, i);
current = current->next;
}
return prefix;
}
int main() {
cout << "Longest common prefix: " << result << endl;
return 0;
}


### Output

Longest common prefix: fl


### Approach-2

In this illustration, a linked list of strings is created ("apple", "appreciate", "apex", and "application"). With the head of the linked list, we then run the Longestcommonprefix function to save the outcome in the prefix variable.

Finally, we clean up the memory used for the linked list and display the outcome ("app") to the console.

### Example-2

#include <iostream>
using namespace std;
struct Listnode {
string value;
Listnode* next;
Listnode(string x) : value(x), next(nullptr) {}
};
return "";
}
string prefix = current->value;
while (current) {
string str = current->value;
int i = 0;
while (i < prefix.length() && i < str.length() && prefix[i] == str[i]) {
i++;
}
prefix = prefix.substr(0, i);
if (prefix.empty()) {
return "";
}
current = current->next;
}
return prefix;
}
int main() {
cout << "The longest common prefix is: " << prefix << endl;
delete temp;
}
return 0;
}


### Output

The longest common prefix is: ap


The longest common prefix in a linked list has various advantages −

• Efficiency − In a linked list, where n is the number of nodes, finding the longest common prefix can be done in linear time O(n). Compared to other techniques with higher complexity, this one is very effective in determining the longest common prefix.

• The longest common prefix can be used to examine and manipulate the data given in nodes. It can be used, between other things, to group objects that are similar or to match patterns.

• Can be used to optimise the searching − When looking for a certain string in a very large dataset the longest common prefix can be used to decrease the number of strings that need to be view, therefore making the search more efficient.

• Makes simple to compare strings − As the longest common prefix is the part of two strings that they have in common, it may be utilise to compare different strings.

• Simplifies coding − The implementation of the longest common prefix algorithm only requires a small number of lines of code, making it simple to integrate into larger projects or codebases.

### Drawbacks

• Prefix matching − This is the only use of the longest common prefix algorithm. It can only use to determine longest common prefix of strings in linked list. For example, it cannot used to determine the longest common suffix.

• Trouble managing edge cases − The technique may not be very successful in locating the longest common prefix when linked list has only one node or contains nodes with extremely short strings.

• Not suited for some types of data structures − Linked lists and string arrays are the best candidates for the longest common prefix technique. For other data structures with more complex topologies, such trees or graphs, it might not be the ideal strategy.

• Case sensitivity − The algorithm does not recognize "apple" and "Apple" as having the same prefix since it is case sensitive. This could pose issues in various circumstances.

• Additional space − If memory is constrained, then your algorithm's need for extra space to store the prefix string and do string comparisons could become problematic.

## Conclusion

In conclusion, good tool for locating longest common prefix of strings in linked list is longest common prefix algorithm. Due to its efficiency, it is good for handling huge datasets and has variety of uses, such as string comparison, data manipulation, and search engine optimization.

Like most of the algorithm, it has various drawbacks, such as the inability to handle edge cases and the restriction to prefix matching. The algorithm is also case sensitive, which could be a problem in some circumstances. The benefits of the longest common prefix algorithm make it a valuable tool to have in a programmer's toolbox when working with linked lists of strings, despite these disadvantages.

Updated on: 10-May-2023

201 Views