[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:
- We will compare all letters and then wherever we find any of them isn't matching, we stop and return the matching string.
Algorithm:
- If length of whole array is 0, then return empty string.
- 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:
Let me know in the comments how would you make it more efficient.
Comments
Post a Comment