Lexicographically smallest string obtained after concatenating array
Last Updated :
01 Feb, 2023
Given n strings, concatenate them in an order that produces the lexicographically smallest possible string.
Examples:
Input : a[] = ["c", "cb", "cba"]
Output : cbacbc
Possible strings are ccbcba, ccbacb,
cbccba, cbcbac, cbacbc and cbaccb.
Among all these strings, cbacbc is
the lexicographically smallest.
Input : a[] = ["aa", "ab", "aaa"]
Output : aaaaaab
One might think that sorting the given strings in the lexicographical order and then concatenating them produces the correct output. This approach produces the correct output for inputs like ["a", "ab", "abc"]. However, applying this method on ["c", "cb", "cba"] produces the wrong input and hence this approach is incorrect.
The correct approach is to use a regular sorting algorithm. When two strings a and b are compared to decide if they have to be swapped or not, do not check if a is lexicographically smaller than b or not. Instead check if appending b at the end of a produces a lexicographically smaller string or appending a at the end of b does.
This approach works because we want the concatenated string to be lexicographically small, not the individual strings to be in the lexicographical order.
Steps to solve this problem:
1. sort the string a from start index to end index.
2. declare an answer string as blank.
3. iterate through i=0 till n:
*update answer to answer+arr[i].
4. return answer.
Implementation:
C++
// CPP code to find the lexicographically
// smallest string
#include <bits/stdc++.h>
using namespace std;
// Compares two strings by checking if
// which of the two concatenations causes
// lexicographically smaller string.
bool compare(string a, string b)
{
return (a+b < b+a);
}
string lexSmallest(string a[], int n)
{
// Sort strings using above compare()
sort(a, a+n, compare);
// Concatenating sorted strings
string answer = "";
for (int i = 0; i < n; i++)
answer += a[i];
return answer;
}
// Driver code
int main()
{
string a[] = { "c", "cb", "cba" };
int n = sizeof(a)/sizeof(a[0]);
cout << lexSmallest(a, n);
return 0;
}
Java
// Java code to find the lexicographically
// smallest string
class GFG {
// function to sort the
// array of string
static void sort(String a[], int n)
{
//sort the array
for(int i = 0;i < n;i++)
{
for(int j = i + 1;j < n;j++)
{
// comparing which of the
// two concatenation causes
// lexicographically smaller
// string
if((a[i] + a[j]).compareTo(a[j] + a[i]) > 0)
{
String s = a[i];
a[i] = a[j];
a[j] = s;
}
}
}
}
static String lexsmallest(String a[], int n)
{
// Sort strings
sort(a,n);
// Concatenating sorted strings
String answer = "";
for (int i = 0; i < n; i++)
answer += a[i];
return answer;
}
// Driver code
public static void main(String args[])
{
String a[] = {"c", "cb", "cba"};
int n = 3;
System.out.println("lexicographically smallest string = "
+ lexsmallest(a, n));
}
}
// This code is contributed by Arnab Kundu
Python 3
# Python 3 code to find the lexicographically
# smallest string
def lexSmallest(a, n):
# Sort strings using above compare()
for i in range(0,n):
for j in range(i+1,n):
if(a[i]+a[j]>a[j]+a[i]):
s=a[i]
a[i]=a[j]
a[j]=s
# Concatenating sorted strings
answer = ""
for i in range( n):
answer += a[i]
return answer
# Driver code
if __name__ == "__main__":
a = [ "c", "cb", "cba" ]
n = len(a)
print(lexSmallest(a, n))
# This code is contributed by vibhu karnwal
C#
// C# code to find
// the lexicographically
// smallest string
using System;
class GFG {
// function to sort the
// array of string
static void sort(String []a, int n)
{
//sort the array
for(int i = 0;i < n;i++)
{
for(int j = i + 1;j < n;j++)
{
// comparing which of the
// two concatenation causes
// lexicographically smaller
// string
if((a[i] + a[j]).CompareTo(a[j] +
a[i]) > 0)
{
String s = a[i];
a[i] = a[j];
a[j] = s;
}
}
}
}
static String lexsmallest(String []a, int n)
{
// Sort strings
sort(a,n);
// Concatenating sorted
// strings
String answer = "";
for (int i = 0; i < n; i++)
answer += a[i];
return answer;
}
// Driver code
public static void Main()
{
String []a = {"c", "cb", "cba"};
int n = 3;
Console.Write("lexicographically smallest string = "
+ lexsmallest(a, n));
}
}
// This code is contributed by nitin mittal
JavaScript
<script>
// Javascript code to find the lexicographically
// smallest string
// function to sort the
// array of string
function sort(a,n)
{
// sort the array
for(let i = 0;i < n;i++)
{
for(let j = i + 1;j < n;j++)
{
// comparing which of the
// two concatenation causes
// lexicographically smaller
// string
if((a[i] + a[j])>(a[j] + a[i]) )
{
let s = a[i];
a[i] = a[j];
a[j] = s;
}
}
}
}
function lexsmallest(a,n)
{
// Sort strings
sort(a,n);
// Concatenating sorted strings
let answer = "";
for (let i = 0; i < n; i++)
answer += a[i];
return answer;
}
// Driver code
let a=["c", "cb", "cba"];
let n = 3;
document.write("lexicographically smallest string = "
+ lexsmallest(a, n));
// This code is contributed by rag2127
</script>
Complexity Analysis:
- Time complexity : The above code runs in O(M * N * logN) where N is number of strings and M is maximum length of a string.
- Auxiliary Space: O(n)
Similar Reads
DSA Tutorial - Learn Data Structures and Algorithms
DSA (Data Structures and Algorithms) is the study of organizing data efficiently using data structures like arrays, stacks, and trees, paired with step-by-step procedures (or algorithms) to solve problems effectively. Data structures manage how data is stored and accessed, while algorithms focus on
7 min read
Quick Sort
QuickSort is a sorting algorithm based on the Divide and Conquer that picks an element as a pivot and partitions the given array around the picked pivot by placing the pivot in its correct position in the sorted array. It works on the principle of divide and conquer, breaking down the problem into s
12 min read
Merge Sort - Data Structure and Algorithms Tutorials
Merge sort is a popular sorting algorithm known for its efficiency and stability. It follows the divide-and-conquer approach. It works by recursively dividing the input array into two halves, recursively sorting the two halves and finally merging them back together to obtain the sorted array. Merge
14 min read
SQL Commands | DDL, DQL, DML, DCL and TCL Commands
SQL commands are crucial for managing databases effectively. These commands are divided into categories such as Data Definition Language (DDL), Data Manipulation Language (DML), Data Control Language (DCL), Data Query Language (DQL), and Transaction Control Language (TCL). In this article, we will e
7 min read
Bubble Sort Algorithm
Bubble Sort is the simplest sorting algorithm that works by repeatedly swapping the adjacent elements if they are in the wrong order. This algorithm is not suitable for large data sets as its average and worst-case time complexity are quite high.We sort the array using multiple passes. After the fir
8 min read
Breadth First Search or BFS for a Graph
Given a undirected graph represented by an adjacency list adj, where each adj[i] represents the list of vertices connected to vertex i. Perform a Breadth First Search (BFS) traversal starting from vertex 0, visiting vertices from left to right according to the adjacency list, and return a list conta
15+ min read
Data Structures Tutorial
Data structures are the fundamental building blocks of computer programming. They define how data is organized, stored, and manipulated within a program. Understanding data structures is very important for developing efficient and effective algorithms. What is Data Structure?A data structure is a st
2 min read
Binary Search Algorithm - Iterative and Recursive Implementation
Binary Search Algorithm is a searching algorithm used in a sorted array by repeatedly dividing the search interval in half. The idea of binary search is to use the information that the array is sorted and reduce the time complexity to O(log N). Binary Search AlgorithmConditions to apply Binary Searc
15 min read
Insertion Sort Algorithm
Insertion sort is a simple sorting algorithm that works by iteratively inserting each element of an unsorted list into its correct position in a sorted portion of the list. It is like sorting playing cards in your hands. You split the cards into two groups: the sorted cards and the unsorted cards. T
9 min read
Dijkstra's Algorithm to find Shortest Paths from a Source to all
Given a weighted undirected graph represented as an edge list and a source vertex src, find the shortest path distances from the source vertex to all other vertices in the graph. The graph contains V vertices, numbered from 0 to V - 1.Note: The given graph does not contain any negative edge. Example
12 min read