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
Lexicographically smallest string after M operations Given a string S and integer M. The task is to perform exactly M operations to get lexicographical smallest string. In each operation, select one character optimally from the string and update it with immediate next character ( aaa -> aab ), so that string remain lexicographical smallest.Multiple
7 min read
Lexicographically smallest String formed by extracting single character Given a string array S, the task is to find the lexicographically smallest string that can be formed by extracting a single character in each string from the string array S. Example: Input: S = ["xy", "fd"]Output: "dx"Explanation: The possible strings formed by extracting a single character from eac
5 min read
Maximum occurring lexicographically smallest character in a String Given a string containing lowercase characters. The task is to print the maximum occurring character in the input string. If 2 or more characters appear the same number of times, print the lexicographically (alphabetically) lowest (first) character. Examples: Input: test sample Output: e Explanation
6 min read
Lexicographical concatenation of all substrings of a string Given a string, find the concatenation of all substrings in lexicographic order.Examples:Input : s = "abc"Output : aababcbbccThe substrings of s in lexicographic order are "a", "b", "c", "ab", "abc", "bc". Concatenation of substrings is "a"+"ab"+"abc"+"b"+"bc"+"c" = "aababcbbcc".Input : s = "cba"Out
7 min read
Lexicographically smallest string formed by concatenating any prefix and its mirrored form Given a string str of N characters, the task is to find the lexicographically smallest string that can be formed by concatenating any prefix and its mirrored form. Examples: Input: str = "geeksforgeeks"Output: geeeegExplanation: The lexicographically smallest string can be formed with the prefix "ge
5 min read
Find lexicographically smallest string in at most one swaps Given a string str of length N. The task is to find out the lexicographically smallest string when at most only one swap is allowed. That is, two indices 1 <= i, j <= n can be chosen and swapped. This operation can be performed at most one time. Examples: Input: str = "string" Output: gtrins E
14 min read
Lexicographically smallest String by removing exactly K characters Given a string s consisting of only lowercase characters, the task is to find the lexicographically smallest string after removing exactly k characters from the string. But you have to modify the value of k, i.e., if the length of the string is a power of 2, reduce k by half, else multiply k by 2. Y
15 min read
Lexicographically smallest string formed by removing at most one character Given a string s, the task is to find the lexicographically smallest string that can be formed by removing at most one character from the given string. Examples: Input: s = "abcda" Output: "abca"Explanation: One can remove 'd' to get "abca" which is the lexicographically smallest string possible. In
4 min read
Lexicographically smallest string of length N and sum K Given two integers N and K. The task is to print the lexicographically smallest string of length N consisting of lower-case English alphabets such that the sum of the characters of the string equals K where 'a' = 1, 'b' = 2, 'c' = 3, ..... and 'z' = 26. Examples: Input: N = 5, K = 42 Output: aaamz "
6 min read
Lexicographically smallest anagram of given string in range [L, R] for Q queries Given a string S of size N and an array queries, containing Q queries in the form of L, R. The task is to find the lexicographically smallest anagram of string from L to R for each query. Example: Input: S = "bbaacd"queries[]={{1, 3}, {2, 5}}Output:aabaacd Input: S="bbdfaaacaed"queries[]={{0, 4}, {4
7 min read