NLeetCode Solutions
ProblemsPatternsStatistics
© 2026 Created by Trịnh Minh Nhật
GitHubLeetCode
Related posts
  • 49. Group AnagramsMedium
  • 1. Two SumEasy
  • 13. Roman to IntegerEasy
  • 20. Valid ParenthesesEasy
  • 26. Remove Duplicates from Sorted ArrayEasy

14. Longest Common Prefix

Easy
ArrayStringTrie
Answered: Feb 21, 2026
View on LeetCode

Problem Description

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 "".

Examples

Example 1

Input: strs = ["flower","flow","flight"]
Output: "fl"

Example 2

Input: strs = ["dog","racecar","car"]
Output: ""
Explanation:
There is no common prefix among the input strings.

Constraints

  • 1 <= strs.length <= 200
  • 0 <= strs[i].length <= 200
  • strs[i] consists of only lowercase English letters if it is non-empty.

Solutions

Complexity Analysis

Time Complexity:O(S)orO(n∗m)

Where S is the sum of all characters in all strings in the array, n is the number of strings, and m is the length of the longest string. In the worst case, all strings are the same and we compare each character of each string with the prefix.

Space Complexity:O(1)

We are only using a constant amount of extra space for the prefix variable.

The horizontal scanning approach starts by assuming the longest common prefix is the first string in the array. Then, it iterates through the remaining strings and checks if they start with the current prefix. If a string does not start with the prefix, the prefix is shortened by removing the last character until a common prefix is found or the prefix becomes empty.

Complexity Analysis

Time Complexity:O(S)orO(n∗m)

Where S is the sum of all characters in all strings in the array, n is the number of strings, and m is the length of the longest string. In the worst case, all strings are the same and we compare each character of each string with the first string.

Space Complexity:O(1)

We are only using a constant amount of extra space for the character variable c and the index variable i.

The vertical scanning approach checks each character of the first string against the corresponding characters of the other strings. If a mismatch is found or if any string is shorter than the current index, the function returns the common prefix up to that point.

Complexity Analysis

Time Complexity:O(nlogn∗m)

Where n is the number of strings and m is the length of the longest string. Sorting the array takes O(nlog⁡n)O(n \log n)O(nlogn) time, and comparing the first and last strings takes O(m)O(m)O(m) time.

Space Complexity:O(1)

We are only using a constant amount of extra space for the index variable i and the references to the first and last strings. The sorting operation may require O(n)O(n)O(n) space depending on the sorting algorithm used, but it is generally considered O(1)O(1)O(1) for in-place sorting algorithms.

By sorting the array of strings, the longest common prefix of the entire array must be a prefix of the first and last strings in the sorted order. Therefore, we only need to compare the first and last strings character by character until they differ to find the longest common prefix.

Conclusion

ApproachRatingTime ComplexitySpace ComplexityAdvantagesDisadvantages
Horizontal Scanning
O(S)O(S)O(S)O(1)O(1)O(1)Simple and intuitive — progressively shrinks the prefixMay do unnecessary comparisons if early strings don't share prefix
Vertical Scanning
O(S)O(S)O(S)O(1)O(1)O(1)Efficient early termination when strings differ earlySlightly more complex nested loop structure
Sorting Trick
O(nlog⁡n⋅m)O(n \log n · m)O(nlogn⋅m)O(1)O(1)O(1)Only needs to compare first and last strings after sortingSorting overhead makes it slower than linear approaches

The optimal approach for this problem is Solution 1: Horizontal Scanning, which achieves O(S)O(S)O(S) time complexity and O(1)O(1)O(1) space complexity. It starts with the first string as the prefix and progressively shortens it by comparing against each subsequent string, making it the most straightforward and efficient approach.


Previous13. Roman to Integer
Next20. Valid Parentheses
Related posts
  • 49. Group AnagramsMedium
  • 1. Two SumEasy
  • 13. Roman to IntegerEasy
  • 20. Valid ParenthesesEasy
  • 26. Remove Duplicates from Sorted ArrayEasy
On this page
15 lines
1class Solution:
2 def longestCommonPrefix(self, strs: List[str]) -> str:
3 if len(strs) == 0:
4 return ""
5
6 prefix = strs[0]
7
8 for s in strs[1:]: # loop through the strings starting from the second string
9 while prefix != s[0:len(prefix)]: # check s starts with prefix, can replace with "while not s.startswith(prefix):"
10 prefix = prefix[:-1] # remove the last character from prefix
11
12 if len(prefix) == 0:
13 return ""
14
15 return prefix
14 lines
1class Solution:
2 def longestCommonPrefix(self, strs: List[str]) -> str:
3 if len(strs) == 0:
4 return ""
5
6 for i in range(len(strs[0])): # loop through the characters of the first string
7 c = strs[0][i] # get the current character of the first string
8
9 for s in strs[1:]: # loop through the strings starting from the second string
10 # if the current string is shorter than the current index or the current character does not match, return the common prefix up to the current index
11 if len(s) <= i or s[i] != c:
12 return strs[0][:i]
13
14 return strs[0]
17 lines
1class Solution:
2 def longestCommonPrefix(self, strs: List[str]) -> str:
3 if len(strs) == 0:
4 return ""
5
6 # Sort the array to bring similar prefixes together
7 strs.sort()
8
9 first = strs[0]
10 last = strs[-1]
11
12 i = 0
13 # Compare the first and last strings character by character until they differ
14 while i < len(first) and i < len (last) and first[i] == last[i]:
15 i += 1
16
17 return first[:i]