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.

Logic

The first thing I thought of while reading this was how I could solve this with an ordered set. But sets have a time complexity of O(log n) for most operations, it'd take a O(n) time to convert every element into set and O(n log n) time to find the intersection between them.

The approach that I went with was

  1. Lexographically sort the whole thing This helps ensure that all the strings are sorted by the occurance of each character, regardless of their size.
['car', 'dog', 'racecar']
['flight', 'flow', 'flower']
  1. Check only the first and the last elements. Since we lexographically sorted the strings, it is guranteed that all the string will have the same substrings OR the first/last string will be completely different.
  2. If a different character is encountered while looping through them, return the prefix right then and there.

Code

class Solution {
public:
    string longestCommonPrefix(vector<string>& strs) {
        string prefix = "";

        if (strs.size() == 1) {
            return strs[0];
        }

        sort(strs.begin(), strs.end());

        string first = strs[0];
        string last = strs[strs.size() - 1];

        for (int i = 0; i < min(first.size(), last.size()); i++) {
            if (first[i] != last[i]) return prefix;
            prefix += first[i];
        }

        return prefix;
    }
}