BackmediumStringsAdobe

Galactic Transmission Reconstructor Solution

Problem Statement

Given a list of non‑empty phrases, arrange them in lexicographical order and concatenate them without any separators to obtain the smallest possible string. The input consists of an integer n followed by n lines, each containing a single phrase composed of lowercase English letters. Output the resulting concatenated string.

Example 1
Input
3\nstar\ngalaxy\nnebula
Output
galaxynebulastar

Explanation: Sorting the three phrases lexicographically yields ["galaxy","nebula","star"]. Concatenating them without spaces gives "galaxynebulastar".

Example 2
Input
4\nalpha\nbeta\nalphabet\nbet
Output
alphaalphabetbetbeta

Explanation: Lexicographic order is ["alpha","alphabet","bet","beta"]. Joining them produces "alphaalphabetbetbeta".

Example 3
Input
5\nz\nzz\nzzy\na\naa
Output
aaazzzzzy

Explanation: Sorted order: ["a","aa","z","zz","zzy"]. Concatenation results in "aaazzzzzy".

Constraints

  • 1<=n<=100000
  • 1<=|phrase_i|<=1000
  • All characters are lowercase English letters
  • Total length of all phrases does not exceed 10^6
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

Galactic Transmission Reconstructor — Problem Statement & Solution Guide

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

Problem Description

Given a list of non‑empty phrases, arrange them in lexicographical order and concatenate them without any separators to obtain the smallest possible string. The input consists of an integer n followed by n lines, each containing a single phrase composed of lowercase English letters. Output the resulting concatenated string.

DSA Pattern Breakdown

DSA Pattern Breakdown

"Galactic Transmission Reconstructor"

medium

WHY DOES IT MATTER?

This pattern is essential for problems where the optimal arrangement of elements depends on their pairwise interactions rather than their individual values. It is a fundamental concept in combinatorial optimization and is frequently encountered in problems involving string manipulation, array rearrangement, and resource allocation.

OPTIMIZATION CHALLENGE

The key insight is to use a custom comparator that compares the concatenation of two strings in both orders. This reduces the problem to a standard sorting problem, which can be solved in O(n log n) time. The challenge is to implement the comparator efficiently to avoid excessive string concatenations, which can be optimized by comparing characters one by one.

REAL-WORLD CONNECTION

In distributed systems, when merging logs or data streams from multiple nodes, ensuring the merged output is in a specific order (e.g., lexicographically smallest) can be crucial for efficient compression, deduplication, or human readability. This problem models the challenge of arranging data fragments to achieve a global optimal state based on local pairwise comparisons.

In an interview, clearly explain why standard lexicographical sorting fails and how the custom comparator addresses this. Emphasize the transitivity of the comparator and how it ensures a correct global minimum. Be prepared to discuss edge cases such as duplicate strings and empty strings, and how they affect the sorting process.

COMPLEXITY AT A GLANCE

⏱ Time:O(n log n * m)
💾 Space:O(n * m)

Core Theory — Why This Approach?

The problem of arranging strings to form the lexicographically smallest concatenation is a classic application of custom sorting based on a transitive comparator. The naive approach of simply sorting strings lexicographically (e.g., 'a' before 'b') fails because the relative order of two strings depends on their interaction when concatenated. For instance, while 'b' < 'ba' lexicographically, 'ba' + 'b' = 'bab' is smaller than 'b' + 'ba' = 'bba'. Therefore, the comparison logic must evaluate the concatenated result of two strings in both possible orders: compare s1 + s2 versus s2 + s1. This defines a total order that is transitive, ensuring a stable and correct global minimum.

Interview Questions on This Problem

Q1At a fintech platform, you need to merge multiple transaction logs into a single stream for audit purposes. How would you ensure the merged log is in the most compact lexicographical order to minimize storage overhead, and how does this relate to the 'Galactic Transmission Reconstructor' problem?

This is directly analogous to the string arrangement problem. You would treat each log entry as a string and sort them using a custom comparator that compares the concatenation of two entries in both orders (entry1 + entry2 vs entry2 + entry1). This ensures the final concatenated string is lexicographically smallest, which often correlates with better compression ratios in log storage systems. The key is recognizing that standard lexicographical sorting of individual entries does not guarantee the smallest concatenated result.

Q2In a high-growth engineering startup, you are building a URL shortener. How can you optimize the generation of unique, short codes by arranging character fragments to produce the lexicographically smallest possible ID, and what are the edge cases to consider?

You can model the character fragments as strings and apply the same custom sorting algorithm. The goal is to arrange them to form the smallest possible string. Edge cases include handling empty strings (though the problem states non-empty), ensuring the comparator is transitive to avoid infinite loops in sorting algorithms, and dealing with duplicate strings. The transitivity of the comparator (if a+b < b+a and b+c < c+b, then a+c < c+a) is crucial for the correctness of the sort.

Q3At a global product company, you are designing a system to merge multiple text files into a single document. How would you ensure the merged document is in the lexicographically smallest order, and how would you handle large inputs efficiently?

Use a custom comparator to sort the text files based on the concatenation of their contents. For large inputs, ensure that the comparator is efficient by avoiding unnecessary string concatenations in the comparison logic. You can optimize by comparing characters one by one instead of creating new strings for each comparison. Additionally, consider using a stable sort to maintain the relative order of equal elements, which can be important for deterministic output.

Examples

Example 1

Input

3\nstar\ngalaxy\nnebula

Output

galaxynebulastar

Explanation: Sorting the three phrases lexicographically yields ["galaxy","nebula","star"]. Concatenating them without spaces gives "galaxynebulastar".

Example 2

Input

4\nalpha\nbeta\nalphabet\nbet

Output

alphaalphabetbetbeta

Explanation: Lexicographic order is ["alpha","alphabet","bet","beta"]. Joining them produces "alphaalphabetbetbeta".

Example 3

Input

5\nz\nzz\nzzy\na\naa

Output

aaazzzzzy

Explanation: Sorted order: ["a","aa","z","zz","zzy"]. Concatenation results in "aaazzzzzy".

Constraints

  • 1<=n<=100000
  • 1<=|phrase_i|<=1000
  • All characters are lowercase English letters
  • Total length of all phrases does not exceed 10^6

Optimal Approach & Strategy

Sort the strings using a custom comparator that compares the concatenation of two strings in both orders (s1 + s2 vs s2 + s1). This ensures the final concatenated string is lexicographically smallest, with a time complexity of O(n log n * m), where m is the average length of the strings.

Brute Force Approach

Generate all possible permutations of the strings and concatenate each permutation to find the lexicographically smallest string. This approach is computationally expensive with a time complexity of O(n! * n), making it infeasible for large inputs.

Verified Code Solutions

JavaScript Solution
Time: O(n log n * m)
const fs = require('fs');
const input = fs.readFileSync(0,'utf8').trimEnd().split('\n');
let idx = 0;
function reconstruct(phrases){
    phrases.sort();
    return phrases.join('');
}
const n = parseInt(input[idx++]||'0');
let phrases = [];
for(let i=0;i<n;i++) phrases.push(input[idx++]||'');
process.stdout.write(reconstruct(phrases));

Asked in Top Tech Interviews

Adobe

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.