14. Longest Common Prefix Leetcode solution in JavaSctipt (js)

0

Table of Contents

Problem

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.

Constraints:

  • 1 <= strs.length <= 200
  • 0 <= strs[i].length <= 200
  • strs[i] consists of only lowercase English letters.

Solution

/**
 * @param {string[]} strs
 * @return {string}
 */
var longestCommonPrefix = function(strs) {
    let output = "";
    let smallestlength = strs[0].length;
    for(let i = 0; i < strs.length;i++){
       if(strs[i] < smallestlength)
       {
           smallestlength = strs[i].length;
       }
    }
    for(let j = 0; j < smallestlength; j++){  
        let pass = true;
        let prefix = strs[0][j];
        for(let i = 0; i < strs.length;i++){
            if(prefix != strs[i][j])
            {
                pass = false;
            }
        }
        if(pass){
            output = output+prefix;
        }
        else{
            break;
        }
    }
    return output;
};

Leave a Comment

Skip to content