
Sponsored
In this approach, you start with the first string as a reference and gradually compare it with each subsequent string in the array. The reference prefix is shortened until it matches the prefixes of all strings.
Time Complexity: O(S), where S is the sum of all characters in all strings.
Space Complexity: O(1), as we are using constant extra space.
1#include <iostream>
2#include <vector>
3using namespace std;
4
5string longestCommonPrefix(vector<string>& strs) {
6 if (strs.empty()) return "";
7 string prefix = strs[0];
8 for (int i = 1; i < strs.size(); i++) {
9 while (strs[i].find(prefix) != 0) {
10 prefix = prefix.substr(0, prefix.size() - 1);
11 if (prefix.empty()) return "";
12 }
13 }
14 return prefix;
15}
16
17int main() {
18 vector<string> strs = { "flower", "flow", "flight" };
19 cout << longestCommonPrefix(strs) << endl;
20 return 0;
21}The C++ solution uses the find method to check if the current prefix is a prefix of each string. If not, the prefix is truncated from the end until a common prefix is found or it becomes empty.
This approach involves dividing the array of strings into two halves, recursively finding the longest common prefix for each half, and merging the results. The merge step compares characters from the two strings to find the common prefix.
Time Complexity: O(S), where S is the sum of all characters in the strings.
Space Complexity: O(M*logN), where M is the length of the common prefix and N is the number of strings.
1
This C solution reduces the problem into finding the longest common prefix of smaller sections, leading to a combination of results using a helper function to merge prefixes by character comparison.