-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathlongestCommonPrefix.js
More file actions
executable file
·36 lines (22 loc) · 903 Bytes
/
longestCommonPrefix.js
File metadata and controls
executable file
·36 lines (22 loc) · 903 Bytes
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
// function to find longest common prefix among an array of strings
// example :
// ["flower","flow","flight"] -> "fl"
// ["dog","racecar","car"] -> ""
function longestCommonPrefix(strs) {
if (!strs.length) return "";
for(let i = 0; i < strs[0].length; i++) {
let ch = strs[0][i];
for(let s of strs) {
if(i >= s.length || s[i] !== ch) {
return strs[0].slice(0, i);
}
}
}
return strs[0];
}
// test the function
console.log(longestCommonPrefix(["flower","flow","flight"])); // Output: "fl"
console.log(longestCommonPrefix(["dog","racecar","car"])); // Output: ""
console.log(longestCommonPrefix(["interspecies","interstellar","interstate"])); // Output: "inters"
console.log(longestCommonPrefix(["throne","throne"])); // Output: "throne"
console.log(longestCommonPrefix(["throne","dungeon"])); // Output: ""