14. Longest Common Prefix

Solution

class Solution {
public:
    string longestCommonPrefix(vector<string>& strs) {
        string result = "";
        
        for (int i = 0; i < strs[0].size(); i++) {
            for (int j = 0; j < strs.size(); j++) {
                if (i == strs[j].size() || strs[j][i] != strs[0][i]) {
                    return result;
                }
            }
            
            result += strs[0][i];
        }
        
        return result;
    }
};

Complexity

  • Time Complexity: O(N), where N is the total number of chars to check.
  • Space Complexity: O(N), where N is the size of the common prefix.

All Solutions