Longest Common Prefix
In Longest Common Prefix, your task is to find the longest common prefix string amongst an array of strings.
If there is no common prefix, return an empty string "".
For example, if strs = ["flower","flow","flight"], the longest common prefix is "fl". If strs = ["dog","racecar","car"], there is no common prefix, so the answer is "".
Example Input & Output
Longest common prefix is "fl".
Algorithm Flow

Solution Approach
A straightforward way to solve this problem is to sort the label array and then join the sorted labels with newline characters. That directly mirrors the two things the problem asks for: ordering the labels and formatting them as one multi-line string.
The one detail worth paying attention to is the comparison rule. The examples show that you should preserve the original casing of every label and let the language's direct string ordering decide the result. For example, ["amber", "Citrus Rise", "Bluff"] becomes Bluff\nCitrus Rise\namber, which tells you not to normalize everything to lowercase before sorting. If you lowercase all labels just for comparison, you could change the expected order. So the safest interpretation is to sort the strings as they are and keep the text untouched.
In JavaScript, the solution can stay very small:
The copy created with [...labels] is optional, but it is helpful if you do not want to mutate the original input. After that, join('\n') creates the exact output shape the problem wants. If the list is empty, joining an empty array gives an empty string. If there is only one label, the result is just that label with no extra newline before or after it.
This approach also keeps duplicates automatically. Sorting does not remove repeated values, so if "Aurora Bloom" appears twice, both copies remain in the final string. That matches the sample with duplicate labels.
The time complexity is O(n log n) because the sorting step dominates the work. Joining the strings takes linear time after that. The extra space is O(n) if you create a copy before sorting, plus the final output string itself.
So the full idea is simple but exact: do a normal string sort on the original labels, keep each label unchanged, then connect them with newline characters to produce one final formatted string.
Best Answers
import java.util.*;
class Solution {
public String compose_artisan_labels(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.
