Статья пока доступна только на английском.
Problem Description
Write a function that finds the longest common prefix string among an array of strings.
If there is no common prefix, return an empty string "".
Input: an array of strings.
Output: a string that is the longest common prefix of all strings in the array.
Constraints
- The array contains from 1 to 200 strings
- Each string has from 0 to 200 characters
- Each string consists only of lowercase English letters
Examples
Input: ["flower","flow","flight"]
Answer: "fl"
Solution
To find the common prefix of several strings, we compare characters with the same index in every string, starting from the 0th character. If the characters match, the current character is part of the common prefix. As soon as we find the first mismatch or one of the strings ends, the common prefix is over.
The final algorithm:
- Pick one string from the array to iterate over. For convenience, we can pick the first one.
- Iterate over the chosen string character by character. For each character, run an inner loop that checks whether all strings have the same character at that index.
- If the character at that index is the same in all strings, append it to the result.
- Stop iterating and return the prefix as soon as we hit the first mismatch or exceed the length of any string.
export const longestCommonPrefix = (strs: string[]): string => {
if (strs.length == 0) {
return '';
}
let prefix = '';
const firstStr = strs[0];
for (let i = 0; i < firstStr.length; i++) {
const char = firstStr[i];
for (let j = 0; j < strs.length; j++) {
const str = strs[j];
if (i >= str.length || str[i] != firstStr[i]) {
return prefix;
}
}
prefix += char;
}
return prefix;
};Complexity Analysis
Time Complexity
O(m * n), where n is the number of strings in the array and m is the length of the shortest string.
We iterate over a string and compare the characters at the current index in every string.
Space Complexity
O(1), i.e. constant, since we only allocate memory for a few variables and the resulting string.