14. Longest Common Prefix - Easy
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"
Constraints:
- 1 <= strs.length <= 200
- 0 <= strs[i].length <= 200
- strs[i] consists of only lowercase English letters if it is non-empty
Solution:
var longestCommonPrefix = function(strs) {
let res = '';
let prefix = strs[0];
for (let i = 0; i < prefix.length; i++) {
if (strs.some(str => str[i] !== prefix[i])) {
break;
}
res += prefix[i];
}
return res;
}
Thoughts:
This was a difficult one and I gave up after 30 minutes. The solution above is easy enough to understand. I have solved quite a few problems today so I am tired now and need to stop as I'm not practising as well as I should be. I'd give this a 4/10 for confidence. Should be a medium IMO. I'll come back to it at some point.
Comments
Post a Comment