Last active
March 27, 2022 10:37
-
-
Save tahashieenavaz/4d011fec87ccb911f72fd655a7168c70 to your computer and use it in GitHub Desktop.
Write a function to find the longest common prefix string amongst an array of strings!
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/** | |
* @param {string[]} strs | |
* @return {string} | |
* https://underdash.web.app | |
* https://leetcode.com/problems/longest-common-prefix/ | |
* https://underdash.medium.com/spiral-matrix-javascript-c8aa2bd957e | |
* | |
* Copyright reserved by Taha Shieenavaz (Underdash) | |
*/ | |
const longestCommonPrefix = strs => { | |
let prefix = "" | |
let minLength = strs[0].length | |
let minIndex = 0 | |
let currentChar = null | |
let equalForAll = true | |
for( let i = 1; i < strs.length ; i++ ) { | |
if( strs[i].length < minLength ) { | |
minLength = strs[i].length | |
minIndex = i | |
} | |
} | |
for( let i = 0; i < minLength; i++) { | |
currentChar = strs[minIndex][i] | |
equalForAll = true | |
for( let j = 0; j < strs.length; j++ ) { | |
if( strs[j][i] != currentChar ) { | |
equalForAll = false | |
break | |
} | |
} | |
if( equalForAll ) | |
prefix += currentChar | |
else | |
break | |
} | |
return prefix | |
}; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment