14. Longest Common Prefix ๐ฑ
Difficulty: Easy
- Tags: String
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:
Output:
Example 2:
Input:
Output:
Explanation: There is no common prefix among the input strings.
Constraints
The array
strs
contains at least one string and at most 200 strings.All strings in
strs
consist of lowercase English letters only.
Solution ๐ก
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.
Java
Time Complexity โณ
O(m * n): The time complexity is linear, where
m
is the length of the shortest string andn
is the number of strings in the array.
Space Complexity ๐พ
O(1): The space complexity is constant since we are using only a few variables.
You can find the full solution here.
Last updated