BackmediumStringsRazorpayOracle

Lexicographical Phrase Reconstructor Solution

Problem Statement

Given a collection of disjoint phrases, return the input array as it is already in lexicographically smallest order.

Example 1
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.

Example 2
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.
Live Compiler1 Free Run Available
Loading Editor...
Test Cases & Output
Click "Run" to test your 1 free compile trial!

🚀 Practice this problem

Run code, get AI hints & track streak

Sign Up Free

Lexicographical Phrase Reconstructor — Problem Statement & Solution Guide

StringsMediumMixed
TimeO(n log n)
|
SpaceO(n)

Problem Description

Given a collection of disjoint phrases, return the input array as it is already in lexicographically smallest order.

Examples

Example 1

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.

Example 2

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

JavaScript Solution
Time: O(n log n)
function lexicographicalPhraseReconstructor(phrases) {
  if (!phrases.length) return [];
  return phrases.slice().sort((a, b) => a.localeCompare(b)).join(', ');
}

Asked in Top Tech Interviews

RazorpayOracle

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.