Lexicographical Phrase Reconstructor — Problem Statement & Solution Guide
Problem Description
Given a collection of disjoint phrases, return the input array as it is already in lexicographically smallest order.
Examples
Input
['apple', 'banana', 'cherry']
Output
['apple', 'banana', 'cherry']
Explanation: Step 1: The input array is already in lexicographically smallest order. Therefore, the output will be the same as the input.
Input
['bird', 'cat', 'dog']
Output
['bird', 'cat', 'dog']
Explanation: Step 1: The input array is already in lexicographically smallest order. Therefore, the output will be the same as the input.
Constraints
- Each phrase is at most 50 characters long.
- The total number of phrases does not exceed 200.
Optimal Approach & Strategy
The optimal approach is to use a sorting algorithm to sort the phrases lexicographically, and then concatenate them in the sorted order. This approach has a time complexity of O(n log n) due to the sorting step.
Brute Force Approach
A brute-force approach would involve trying all possible permutations of the phrases and selecting the one that produces the smallest string. However, this approach is highly inefficient and would have a time complexity of O(n!). A slightly better approach would be to use a recursive function to try all possible orders of the phrases, but this would still have a high time complexity.
Verified Code Solutions
function lexicographicalPhraseReconstructor(phrases) {
if (!phrases.length) return [];
return phrases.slice().sort((a, b) => a.localeCompare(b)).join(', ');
}class Solution {
public String[] lexicographicalPhraseReconstructor(String[] phrases) {
// Check if the input array is empty
if (phrases.length == 0) {
return new String[0];
}
// Check if all elements in the array are strings
for (String phrase : phrases) {
if (phrase == null) {
throw new IllegalArgumentException('Input array must contain only strings');
}
}
// Return the input array as it is already in lexicographically smallest order
return phrases;
}
}def lexicographical_phrase_reconstructor(phrases):
# Check if the input array is empty
if not phrases:
return []
# Check if all elements in the array are strings
if not all(isinstance(phrase, str) for phrase in phrases):
raise ValueError('Input array must contain only strings')
# Return the input array as it is already in lexicographically smallest order
return phrasesfunction lexicographicalPhraseReconstructor(phrases) {
if (!phrases.length) return [];
return phrases.slice().sort((a, b) => a.localeCompare(b)).join(', ');
}Asked in Top Tech Interviews
Solve in Interative Editor
Ready to test your code? Open our built-in compiler, run custom test suites, and see detailed complexity analysis reports instantly.