Skip to content

Instantly share code, notes, and snippets.

@ChitreshApte
Last active January 22, 2021 10:13
class Solution {
public:
string longestCommonPrefix(vector<string>& strs) {
//edge case, empty array
if(strs.empty()) return "";
//empty string
string ans;
//200 is the max possible length of string, as per constraints
int minLen = 200;
//finding minLen
for(string s : strs)
minLen = min(minLen, (int)s.length());
//checking characters from index 0 to minLen-1
for(int i=0; i<minLen; i++)
{
//character at index i of first string
char ch = strs[0][i];
//looping throgh all the strings
for(int j=0; j<strs.size(); j++)
{
//the character differs
if(strs[j][i] != ch)
{
//ans cannot be expanded further
return ans;
}
}
//ch is same across all strings, expand our answer
ans.push_back(ch);
}
return ans;
}
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment