Problem Description
Given an array of strings, find the longest common prefix string amongst them. If there is no common prefix, return an empty string.
Key Insights
- Compare characters of the strings one column at a time (vertical scanning).
- The longest possible prefix is limited by the length of the shortest string in the array.
- As soon as a mismatch is found, the prefix up to that point is the answer.
- Handle edge cases such as an empty input array or strings with no common prefix.
Space and Time Complexity
Time Complexity: O(N*M) where N is the number of strings and M is the length of the shortest string. Space Complexity: O(1) additional space (ignoring output space).
Solution
We use the vertical scanning approach:
- If the input array is empty, return an empty string.
- Iterate character by character over the first string.
- For each character, compare it with the corresponding character in each of the other strings.
- If a mismatch or end of any string is encountered, return the substring from the start up to the current index.
- If no mismatch is found, the entire first string is the common prefix.
This solution ensures that we only traverse the necessary part of the strings and stops early if a discrepancy is discovered.