> For the complete documentation index, see [llms.txt](https://adit0503.gitbook.io/leetcode/llms.txt). Markdown versions of documentation pages are available by appending `.md` to page URLs; this page is available as [Markdown](https://adit0503.gitbook.io/leetcode/14.-longest-common-prefix.md).

# 14. 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 `""`.

## :innocent: [Solution](https://leetcode.com/problems/longest-common-prefix/)

{% tabs %}
{% tab title="O(nS)" %}

```python
#Horizontal Scanning

class Solution:
    def longestCommonPrefix(self, strs: List[str]) -> str:
        
        if len(strs) == 0:
            return ""
        
        prefix = strs[0]
        
        for i in range(1,len(strs)): #O(n)
            while(strs[i].find(prefix) != 0): #O(S)
                prefix = prefix[0:len(prefix)-1]
            
            if len(prefix) == 0:
                return ""
        
        return prefix
        
```

{% endtab %}

{% tab title="O(nS)" %}

```python
#Vertical Scanning

class Solution:
    def longestCommonPrefix(self, strs: List[str]) -> str:
        
        if len(strs) == 0:
            return ""
        
        prefix = ""
        
        for i in range(len(strs[0])):
            c = strs[0][i]
            for j in range(1,len(strs)):
                if i >= len(strs[j]):
                    return prefix
                if c != strs[j][i]:
                    return prefix
            prefix += c
        
        return prefix
```

{% endtab %}
{% endtabs %}
