diff --git a/LeetcodeProblems/Algorithms/Longest_Common_Prefix.js b/LeetcodeProblems/Algorithms/Longest_Common_Prefix.js new file mode 100644 index 0000000..a992179 --- /dev/null +++ b/LeetcodeProblems/Algorithms/Longest_Common_Prefix.js @@ -0,0 +1,34 @@ +/** +Longest Common Prefix +https://leetcode.com/problems/longest-common-prefix/ + +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: "" +Explanation: There is no common prefix among the input strings. + +*/ + +/** + * @param {string[]} strs + * @return {string} + */ + var longestCommonPrefix = function(strs) { + if(strs.length === 0) return ""; + + return strs.reduce((result, curr)=>{ + let i = 0; + while(result[i] && curr[i] && result[i] === curr[i]) i++; + return result.slice(0, i); + }); +}; + +module.exports.longestCommonPrefix = longestCommonPrefix; \ No newline at end of file diff --git a/LeetcodeProblemsTests/Algorithms/Longest_Common_Prefix_Test.js b/LeetcodeProblemsTests/Algorithms/Longest_Common_Prefix_Test.js new file mode 100644 index 0000000..d1d5e46 --- /dev/null +++ b/LeetcodeProblemsTests/Algorithms/Longest_Common_Prefix_Test.js @@ -0,0 +1,11 @@ + +const assert = require('assert'); +const longestCommonPrefix = require('../../LeetcodeProblems/Algorithms/Longest_Common_Prefix').longestCommonPrefix; + +function test() { + assert.equal(longestCommonPrefix(["flower","flow","flight"]), "fl"); + assert.equal(longestCommonPrefix(["dog","racecar","car"]), ""); + assert.equal(longestCommonPrefix([]), ""); +} + +module.exports.test = test; diff --git a/README.md b/README.md index 66811a5..07daedb 100644 --- a/README.md +++ b/README.md @@ -79,6 +79,7 @@ To run a specific problem in your console run `node ` (e.g. | [Binary Gap ](/LeetcodeProblems/Algorithms/Binary_Gap.js) | Easy | https://leetcode.com/problems/binary-gap/ | | [Binary Gap ](/LeetcodeProblems/Algorithms/Binary_Gap.js) | Easy | https://leetcode.com/problems/binary-gap/ | | [Majority Element](/LeetcodeProblems/Algorithms/Majority_Element.js) | Easy | https://leetcode.com/problems/majority-element/ | +| [Longest Common Prefix](/LeetcodeProblems/Algorithms/Longest_Common_Prefix.js) | Easy | https://leetcode.com/problems/longest-common-prefix/ | | [Two Sum](/LeetcodeProblems/Algorithms/2Sum.js) | Easy | https://leetcode.com/problems/two-sum/ | | [Tic Tac Toe ](/LeetcodeProblems/Algorithms/Tic_Tac_Toe.js) | | | | [Permutations With Duplicates ](/LeetcodeProblems/Algorithms/Permutations_With_Duplicates.js) | | |