[LeetCode] Longest Common Prefix

 Hi, In this post we are going to be learning about how to solve the LeetCode Array Question: Longest Common Prefix.

Problem Statement:

Write a function to find the longest common string amongst an array of strings. If there is no common prefix, return an empty string.

Test Case:

Input: ["flower", "flow", "flight"] | Output: "fl"

Input: ["a"] | Output: "a"

Input: [""] | Output: ""

Input: ["dog", "racecar", "car"] | Output: ""


Approach - Vertical Scanning:

  1. We will compare all letters and then wherever we find any of them isn't matching, we stop and return the matching string.
Algorithm:
  1. If length of whole array is 0, then return empty string.
  2. The outer loop runs from 0 to length of first element of the array while inner loop runs from 1 to length of the array. Visualize from the below image:

JavaScript Code:



Let me know in the comments how would you make it more efficient.

Comments

Popular

How To Create MySQL Table with SequelizeJS

How To Read CSV Files in Java as Maven Project

How To Create A Hibernate Project in Maven