Longest Common Prefix

Problem

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 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.

Constraints:

  • 0 <= strs.length <= 200
  • 0 <= strs[i].length <= 200
  • strs[i] consists of only lower-case English letters.

My Solution

success
const longestCommonPrefix = (strs) => {
	let result = '';
	let single = [];
	let match = [];
	let i = 0;
	while (single.length === match.length) {
		single = strs.map((str) => str[i]);
		match = single.filter((ltr) => ltr === single[i]);
		single.length === match.length && (result += match[0]);
		i++;
	}
	return result;
};
success
const longestCommonPrefix = (strs) => {
	if (strs.length === 0) return '';
	let prefix = strs[0];
	for (let i = 1; i < strs.length; i++) {
		while (strs[i].indexOf(prefix) !== 0) {
			prefix = prefix.substring(0, prefix.length - 1);
		}
	}
	return prefix;
};