What is Longest Common Prefix?
The Longest Common Prefix (LCP) of a group of strings is the longest prefix shared by every string. If no common prefix exists, the result is an empty string.
This problem frequently appears in coding interviews and is useful in autocomplete systems, dictionaries, search engines, and text processing.
Example
Input:
["flower", "flow", "flight"]
Output:
"fl"
Algorithm
- Take the first string as the initial prefix.
- Compare it with every remaining string.
- If the current string doesn't start with the prefix, remove the last character from the prefix.
- Repeat until every string begins with the prefix.
- Return the final prefix.
Complexity Analysis
- Best Case: O(n)
- Average Case: O(n × m)
- Worst Case: O(n × m)
- Space Complexity: O(1)