Skip to main content

14 Longest Common Prefix Leetcode Problem Javascript Solution

Longest Common Prefix
Easy
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: ["flower","flow","flight"]
Output: "fl"
Example 2:
Input: ["dog","racecar","car"]
Output: ""
Explanation: There is no common prefix among the input strings.
Note:
All given inputs are in lowercase letters a-z.

Javascript Solution to the Longest Common Prefix Problem

const longestPrefix = arr => {
  if (arr.length === 0) {
    return "";
  }
  if (arr.length === 1) {
    return arr[0];
  }
  let end = 0;
  let check = false
  for (let j = 0; j < arr[0].length; j++){
    for (let i = 1; i < arr.length; i++) {
      if (arr[0][j] !== arr[i][j]) {
        check = true;
        break;
      }
    }
    if (check) {
      break;
    }
    end++;
  }
  return (arr[0].slice(0, end))
}

Test Input

console.log(longestPrefix(["Jabine", "Jabinder", "Jabbong"]))

Output

Jab
Run the code here: https://repl.it/@VinitKhandelwal/longest-prefix-javascript

Comments