DEV Community

Cover image for Leet Code - Longest Common Prefix
Anuj Srivastav
Anuj Srivastav

Posted on

Leet Code - Longest Common Prefix

Problem Statement

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 "".

Algorithm

  • if array is empty, return a prefix of empty string Or if
    array has 1 word, return the whole word.

  • Iterate through letter of first word of Array , and compare
    those letters to same Indexed letter to other world.

Example

   let strs = ["flower","flow","flight"]
   So What above line meaning is -
   str[0][0] === str[1][0],
   str[0][1] === str[1][1] and so on....  
Enter fullscreen mode Exit fullscreen mode
  • if the letters match continue to next set of letters
    otherwise return the prefix

  • If the letter is no longer matching then the first word
    will mark where the longest common prefix is, so
    we add to our empty string.

First Try to Solve Problem using Algorithm

Javascript Function for Longest Common Prefix

/**
 * @param {string[]} strs
 * @return {string}
 */
var longestCommonPrefix = function(strs) {
let result = "";
//array is empty, return a prefix of empty string
if (strs.length === 0) {return ""}

//array has 1 word, return the whole word
if (strs.length === 1) {return strs[0]}

//Iterate through letter of first word of Array
for(let i=0 ; i<strs[0].length ; i++){
//compare those letters to same Indexed letter to other world.
 for(let j=1 ; j< strs.length ; j++){
 if(strs[0][i] == strs[j][i]){
     continue;
 }else{
     return result
 }
 }

/*If the letter is no longer matching then the first word 
  will mark where the longest common prefix is, so 
  we add to our empty string*/
result += strs[0][i];
}
return result;    
};

Enter fullscreen mode Exit fullscreen mode

Test Cases

Input: strs = ["flower","flow","flight"]
Output: "fl"

Input: strs = ["dog","racecar","car"]
Output: ""

Input: strs = ["",""]
Output: ""

Top comments (3)

Collapse
 
frankwisniewski profile image
Frank Wisniewski
"use strict";
  var longestCommonPrefix = (strs) =>
    strs.join()
      .match(/^(?<prefix>[\w\p{Emoji}]*)[\w\p{Emoji}]*(?:,\1[\w\p{Emoji}]*)*$/u)
        .groups.prefix

  let strs = ["flower","flow","flight"]

  console.log(
    longestCommonPrefix(strs)
  )
Enter fullscreen mode Exit fullscreen mode
Collapse
 
orimdominic profile image
Orim Dominic Adah

Nice.

It would be great if you added the question to the article for context.

👍

Collapse
 
anuj8126 profile image
Anuj Srivastav

Added Problem Statement to the article @orimdominic . for more clarity you can visit
leetcode.com/problems/longest-comm...