14. Longest Common Prefix ๐ฑ
Last updated
Was this helpful?
Last updated
Was this helpful?
Difficulty: Easy
- Tags: String
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 "".
Example 1:
Input:
Output:
Example 2:
Input:
Output:
Explanation: There is no common prefix among the input strings.
The array strs
contains at least one string and at most 200 strings.
All strings in strs
consist of lowercase English letters only.
To solve this problem, we compare characters of each string in the array and find the longest common prefix by checking each character in the strings until a mismatch is found.
O(m * n): The time complexity is linear, where m
is the length of the shortest string and n
is the number of strings in the array.
O(1): The space complexity is constant since we are using only a few variables.
You can find the full solution .