LeetCode 14: Longest Common Prefix Explained

LeetCode 14: Longest Common Prefix Explained

LeetCode 14: Longest Common Prefix Explained

The "Longest Common Prefix" problem is a common LeetCode challenge that asks you to find the longest common prefix string amongst an array of strings. In this post, I'll explain how to solve this problem efficiently in Python.

Problem Overview

Given an array of strings `strs`, find the longest common prefix string amongst all strings in the array.

If there is no common prefix, return an empty string "".

Solution

Here's a Python function to find the longest common prefix:

def longest_common_prefix(strs):
    if not strs:
        return ""

    prefix = strs[0]
    for i in range(1, len(strs)):
        while strs[i].find(prefix) != 0:
            prefix = prefix[:-1]
            if not prefix:
                return ""
    return prefix

This function works by first checking if the input list of strings is empty. If it is, it returns an empty string. Otherwise, it initializes the `prefix` variable to the first string in the list. It then iterates through the remaining strings in the list, and for each string, it checks if the current `prefix` is a prefix of that string. If it is not, it shortens the `prefix` by one character at a time until it is a prefix of the current string or until it becomes empty. If the `prefix` becomes empty, it means there is no common prefix, so the function returns an empty string. Finally, if the loop completes without finding an empty prefix, it means the current `prefix` is the longest common prefix, so the function returns it.

Test Cases

>>> longest_common_prefix(["flower","flow","flight"])
"fl"
>>> longest_common_prefix(["dog","racecar","car"])
""
>>> longest_common_prefix([""])
""
>>> longest_common_prefix(["a"])
"a"
>>> longest_common_prefix(["ab", "a"])
"a"

Conclusion

In this post, I've explained how to solve the LeetCode "Longest Common Prefix" problem efficiently in Python. This approach is generally considered one of the more optimal solutions. I hope this explanation was helpful. If you have any questions, please leave a comment below.

Comments

Popular posts from this blog

LeetCode Problem #10: Regular Expression Matching - Explanation and Solutions in Python and JavaScript

LeetCode Problem #1: Two Sum - Explanation and Solutions in Python and JavaScript

LeetCode Problem #2: Add Two Numbers - Explanation and Solutions in Python and JavaScript