Leetcode 14. Longest Common Prefix
The problem requires you to 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 “”.
Example:
Input: strs = ["flower","flow","flight"]
Output: "fl"
Q: Can the input array be empty? A: Yes, if the input array is empty, the function should return an empty string.
Q: Are all strings in the array non-empty? A: The problem does not explicitly say, so we should handle the case where strings could potentially be empty.
Q: Can the strings contain special characters or be of varying lengths? A: Yes, the strings can contain any characters and have varying lengths.
Q: Is the function case-sensitive? A: Yes, the function should treat uppercase and lowercase characters as different characters (case-sensitive).
Q: What should be returned if strings share no common prefix? A: Return an empty string “”.
#include <iostream>
#include <vector>
#include <string>
using namespace std;
string longestCommonPrefix(vector<string>& strs) {
if (strs.empty()) return ""; // Return empty string for empty input array
string prefix = strs[0]; // Take the first string as the initial prefix
for (size_t i = 1; i < strs.size(); ++i) {
// Compare current prefix with each string
while (strs[i].find(prefix) != 0) {
// Shrink prefix until it matches the beginning of str[i]
prefix = prefix.substr(0, prefix.length() - 1);
if (prefix.empty()) return ""; // No common prefix
}
}
return prefix;
}
int main() {
vector<string> strs = {"flower", "flow", "flight"};
cout << "Longest Common Prefix: " << longestCommonPrefix(strs) << endl; // Output: "fl"
return 0;
}
The implementation tackles comparisons pairwise, optimizing by reducing the size of the prefix as soon as mismatch detected. This strategy covers edge cases like empty arrays and unequal lengths efficiently.
Got blindsided by a question you didn’t expect?
Spend too much time studying?
Or simply don’t have the time to go over all 3000 questions?