Problem
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 ""
.
OR
Given a sentence, give Longest Sequence Of Prefix Shared By All The Words In A String
Longest common prefix for a pair of strings S1 and S2 is the longest string S which is the prefix of both S1 and S2.
As an example, longest common prefix of “abcdefgh” and “abcefgh” is “abc”.
This interesting problem was asked in the Google interview for software engineer. This problem is bit tricky, it looks difficult but actually it is simple problem.
Examples
Example 1:
|
|
Example 2:
|
|
Solution
Method 1 - Using indexOf
To find the longest common prefix among an array of strings, we can follow these steps:
- Edge Cases: Handle edge cases where the input array is empty or contains only one string.
- Horizontal Scanning: Compare characters of each string in the array sequentially, checking for the common prefix.
|
|
Code
|
|
Complexity
- ⏰ Time complexity:
O(n * m)
where n is the number of strings and m is length of string - 🧺 Space complexity:
O(1)