LeetCode: 14. Longest Common Prefix
The Problem
Write a function to find the longest common prefix string amongst an array of strings.
If there is no common prefix, return an empty string ""
.
Examples
Example 1:
Input: strs = ["flower","flow","flight"]
Output: "fl"
Example 2:
Input: strs = ["dog","racecar","car"]
Output: ""
Explanation: There is no common prefix among the input strings.
Constraints:
1 <= strs.length <= 200
0 <= strs[i].length <= 200
strs[i]
consists of only lowercase English letters.
The solution
We opted for a simple approach using a for loop, this was the result:
string longestCommonPrefix(vector<string>& strs) {
sort(strs.begin(), strs.end());
string &front = strs.front();
string &back = strs.back();
int maxSize = min(front.size(), back.size());
string ans = "";
for(int i = 0; i < maxSize; ++i){
if(front[i] != back[i]) break;
ans += front[i];
}
return ans;
}
ðŸ§
Github with all the solution including test cases.
Let's break down this code:
sort(strs.begin(), strs.end())
: Here, we're sorting the elements in the array in ascending order.string &front = strs.front()
: This line retrieves the first element of the vector.string &back = strs.back()
: Similarly, this line retrieves the last element of the vector.maxSize = min(front.size(), back.size())
: Here, we determine the minimum size of the elements to use in our subsequent loop.for(int i = 0; i < maxSize; ++i)
: This loop is designed to check for similarities within elements from the beginning up to themaxSize
.if(front[i] != back[i]) break
: Within this step, we compare the characters of the first and last elements at positioni
. If they differ, the loop terminates.ans += front[i]
: Here, we append the character at positioni
from thefront
string to theans
string.return ans
: Finally, we return the resultant stringans
.
We exclusively compare the first and last elements because the preceding sorting ensures that the words are arranged by their similarities. For example:
A = {"hello", "hell", "hellfire", "heman"}
After sorting: A = {"hell", "hellfire", "hello", "heman"}
Applying the algorithm yields "he" as the result.