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:

  1. sort(strs.begin(), strs.end()): Here, we're sorting the elements in the array in ascending order.
  2. string &front = strs.front(): This line retrieves the first element of the vector.
  3. string &back = strs.back(): Similarly, this line retrieves the last element of the vector.
  4. maxSize = min(front.size(), back.size()): Here, we determine the minimum size of the elements to use in our subsequent loop.
  5. for(int i = 0; i < maxSize; ++i): This loop is designed to check for similarities within elements from the beginning up to the maxSize.
  6. if(front[i] != back[i]) break: Within this step, we compare the characters of the first and last elements at position i. If they differ, the loop terminates.
  7. ans += front[i]: Here, we append the character at position i from the front string to the ans string.
  8. return ans: Finally, we return the resultant string ans.

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.