Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
34 changes: 34 additions & 0 deletions LeetcodeProblems/Algorithms/Longest_Common_Prefix.js
Original file line number Diff line number Diff line change
@@ -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;
11 changes: 11 additions & 0 deletions LeetcodeProblemsTests/Algorithms/Longest_Common_Prefix_Test.js
Original file line number Diff line number Diff line change
@@ -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;
1 change: 1 addition & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -79,6 +79,7 @@ To run a specific problem in your console run `node <problem_file_path>` (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) | | |
Expand Down