-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathLongestCommonPrefix.js
More file actions
23 lines (22 loc) · 1.02 KB
/
Copy pathLongestCommonPrefix.js
File metadata and controls
23 lines (22 loc) · 1.02 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
/**
* @param {string[]} strs
* @return {string}
*/
//Plan - Iterate over strs[], using first word as prefix
//Runtime: 62 ms, faster than 93.09% of JavaScript online submissions for Longest Common Prefix.
//Memory Usage: 42.8 MB, less than 44.56% of JavaScript online submissions for Longest Common Prefix.
var longestCommonPrefix = function (strs) {
if (strs.length < 1) return "";
let limit = strs[0].length;
for (let x = 1; x < strs.length; x++) {
for (let y = 0; y < limit; y++)
if (strs[0][y] != strs[x][y]) { //compare first word to rest
limit = y;
}
}
return strs[0].slice(0, limit);
};
console.log(longestCommonPrefix(["flower", "flow", "flight"]));
console.log(longestCommonPrefix(["dog", "racecar", "car"]));
console.log(longestCommonPrefix(["a"]));
console.log(longestCommonPrefix([""]));