Longest Common Prefix is a question asked in many interviews including FAANG companies.
The question for an algorithm is,
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: ""
Constraints:
- 1 <= strs.length <= 200
- 0 <= strs[i].length <= 200
- strs[i] consists of only lowercase English letters.
Let's start with the algorithm,
const longestCommonPrefix = function(strs) {
// Return if the string is empty or null
if (strs == null || strs.length === 0) return '' "
const n = strs.length
const m = strs[0].length
// Loop through the letters of the first word
for (let i = 0; i < m; i++) {
// Loop through the next word of array of strings
for (let j = 1; j < n; j++) {
// Check if this character is present in the same position of next string
if (strs[j][i] !== strs[0][i]){
// If not, return the string up to and including the previous character
return strs[0].substring(0,i);
}
}
}
return strs[0]
}
This is the approach which we use to get the correct longest common prefix. I hope you understood the algorithm, if you have any orther way of solveing this then please let us know comment section.
0 Comments