The solution first splits the input string using the comma (,) delimiter to obtain individual strings. The resulting array is then sorted using Arrays.sort(), which arranges the elements in lexicographical ascending order.
After sorting, the strings are concatenated using StringBuilder to produce the final result efficiently.
This approach leverages Java's built-in sorting mechanism and avoids creating multiple intermediate String objects during concatenation.
Java Solution:
import java.util.Arrays;
public class SortAndConcatenateStrings {
public static String sortAndConcatenate(String input) {
String[] words = input.split(",");
Arrays.sort(words);
StringBuilder result = new StringBuilder();
for (String word : words) {
result.append(word.trim());
}
return result.toString();
}
public static void main(String[] args) {
String input = "banana,apple,orange,mango";
String output = sortAndConcatenate(input);
System.out.println(output);
}
}Output: applebananamangoorange
Explanation: The input strings are first sorted alphabetically: apple, banana, mango, orange
These sorted strings are then concatenated to produce: applebananamangoorange
Time Complexity: O(n log n), where n is the number of input strings due to the sorting operation.
Space Complexity: O(n), as the split operation creates an array to store the individual strings.
Key Interview Points: • Arrays.sort() uses an optimized sorting algorithm for object arrays. • StringBuilder is preferred over String concatenation inside loops for better performance. • The trim() method removes leading and trailing spaces that may exist after splitting the input. • A common follow-up question is to perform case-insensitive sorting using a custom Comparator.