After seeing the problem, I determined that iterating the first element of the array and iterating the whole array could be a straightforward approach to solving this problem.
Solution:
Step 01: declare a variable named "prefix" and set the initial value as an empty string("").
Step 02: Check if the given array length is 0 or if the given array is null. If it meets this condition, return the prefix which is an empty string.
Step 03: If the given array does not meet the previous condition, iterate the first element of the array using a for loop and store the elements in the "char" variable.
Step 04: Using another for loop, iterate the given array and this time start the iteration from the second index of the array.
Step 05: If the char and the second element of the given array's char is not equal, then return the prefix.
Step 06: After the second iteration, add the char with the prefix.
Step 07: Return the prefix.
Runtime: 93 ms
Memory: 42.9 MB
/**
* @param {string[]} strs
* @return {string}
*/
var longestCommonPrefix = function(strs) {
let prefix = "";
if(strs.length === 0 || strs === null) return prefix;
for(let i = 0; i < strs[0].length; i++) {
let char = strs[0][i];
for(let j = 1; j < strs.length; j++) {
if(char !== strs[j][i]) {
return prefix;
}
}
prefix += char;
}
return prefix;
};
π Support me: https://www.buymeacoffee.com/abusalehfaysal
π YouTube Channel: https://www.youtube.com/channel/UCW_09Nbobf4URLkAlEo84sw
π PlayList Link: https://youtube.com/playlist?list=PLUnklBXn8NSefCpBaLe39mds6dQx-tDDD
π Connect with me (LinkedIn): https://www.linkedin.com/in/abusalehfaysal
π Follow our LinkedIn Page: https://www.linkedin.com/company/thebacklogprogrammer/
π Like our Facebook page: https://www.facebook.com/thebacklogprogrammer/
π Join our community (Facebook group): https://www.facebook.com/groups/5500588936676942/
π Follow me at: https://www.facebook.com/AbuSalehFaysal10
π Twitter: https://twitter.com/AbuSalehFaysal
π Abu Saleh Faysalβs Blog: https://abusalehfaysal.hashnode.dev/
π Hasnode: https://hashnode.com/@AbuSalehFaysal
π Dev Community: https://dev.to/abusalehfaysal
π freeCodeCamp: https://www.freecodecamp.org/abusalehfaysal
π Medium: https://abusalehfaysal.medium.com/
π GitHub: https://github.com/AbuSalehFaysal
π GitLab: https://gitlab.com/AbuSalehFaysal
Top comments (0)