Longest Common Prefix
Given an array of strings, find the longest common prefix string shared among all of them. If there is no common prefix, return an empty string.
For example, the longest common prefix of ["flower", "flow", "flight"] is "fl". The prefix of ["dog", "racecar", "car"] is "" (no common prefix). A single string ["hello"] has prefix "hello". An empty array returns "".
Finding the longest common prefix is a classic string problem used in autocomplete, IP routing (longest prefix matching), and DNA sequence alignment. It tests character-by-character comparison across multiple strings.
The solution takes the first string as a reference. For each character position, check if all other strings have the same character at that position. If any string is shorter or has a different character, return the prefix found so far.
Edge cases include an empty array (return ""), a single string (return that string), strings with no common characters (return ""), and all strings being identical (return any of them).
Example Input & Output
Longest common prefix is "fl".
Algorithm Flow

Solution Approach
Compare characters at each position across all strings until a mismatch is found.
Handle the empty array case. Take the first string as reference. For each character position, get the character from the first string and check it against the same position in every other string. If any string is too short or has a different character, return the prefix built so far. Otherwise, append the character to the prefix.
Time complexity is O(n * m) where n is the number of strings and m is the shortest string length. Space complexity is O(1) for the prefix.
Best Answers
import java.util.*;
class Solution {
public String artisan_label_string(String[] labels) {
if (labels.length == 0) return "";
String[] sortedArr = labels.clone();
Arrays.sort(sortedArr);
return String.join("\n", sortedArr);
}
}Comments (0)
Join the Discussion
Share your thoughts, ask questions, or help others with this Challenge.
