Find lexicographically smallest string in at most one swaps
Last Updated :
15 Jan, 2024
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
Explanation:
Choose i=1, j=6, string becomes – gtrins. This is lexicographically smallest strings that can be formed.
Input: str = “zyxw”
Output: wyxz
Approach: The idea is to use sorting and compute the smallest lexicographical string possible for the given string. After computing the sorted string, find the first unmatched character from the given string and replace it with the last occurrence of the unmatched character in the sorted string.
For example, let str = “geeks” and the sorted = “eegks”. First unmatched character is in the first place. This character has to swapped such that this character matches the character with sorted string. Resulting lexicographical smallest string. On replacing “g” with the last occurring “e”, the string becomes eegks which is lexicographically smallest.
Below is the implementation of the above approach:
C++
#include <bits/stdc++.h>
using namespace std;
string findSmallest(string s)
{
int len = s.size();
vector< int > loccur(26,-1);
for ( int i = len - 1; i >= 0; --i) {
int chI = s[i] - 'a' ;
if (loccur[chI] == -1) {
loccur[chI] = i;
}
}
string sorted_s = s;
sort(sorted_s.begin(), sorted_s.end());
for ( int i = 0; i < len; ++i) {
if (s[i] != sorted_s[i]) {
int chI = sorted_s[i] - 'a' ;
int last_occ = loccur[chI];
swap(s[i], s[last_occ]);
break ;
}
}
return s;
}
int main()
{
string s = "geeks" ;
cout << findSmallest(s);
return 0;
}
|
Java
import java.util.*;
class GFG{
static String findSmallest( char []s)
{
int len = s.length;
int []loccur = new int [ 26 ];
Arrays.fill(loccur, - 1 );
for ( int i = len - 1 ; i >= 0 ; --i) {
int chI = s[i] - 'a' ;
if (loccur[chI] == - 1 ) {
loccur[chI] = i;
}
}
char []sorted_s = s;
Arrays.sort(sorted_s);
for ( int i = 0 ; i < len; ++i) {
if (s[i] != sorted_s[i]) {
int chI = sorted_s[i] - 'a' ;
int last_occ = loccur[chI];
char temp = s[last_occ];
s[last_occ] = s[i];
s[i] = temp;
break ;
}
}
return String.valueOf(s);
}
public static void main(String[] args)
{
String s = "geeks" ;
System.out.print(findSmallest(s.toCharArray()));
}
}
|
Python3
def findSmallest(s) :
length = len (s);
loccur = [ - 1 ] * 26 ;
for i in range (length - 1 , - 1 , - 1 ) :
chI = ord (s[i]) - ord ( 'a' );
if (loccur[chI] = = - 1 ) :
loccur[chI] = i;
sorted_s = s;
sorted_s.sort();
for i in range (length) :
if (s[i] ! = sorted_s[i]) :
chI = ord (sorted_s[i]) - ord ( 'a' );
last_occ = loccur[chI];
s[i],s[last_occ] = s[last_occ],s[i]
break ;
return "".join(s);
if __name__ = = "__main__" :
s = "geeks" ;
print (findSmallest( list (s)));
|
C#
using System;
class GFG{
static String findSmallest( char []s)
{
int len = s.Length;
int []loccur = new int [26];
for ( int i = 0; i < 26; i++)
loccur[i] = -1;
for ( int i = len - 1; i >= 0; --i) {
int chI = s[i] - 'a' ;
if (loccur[chI] == -1) {
loccur[chI] = i;
}
}
char []sorted_s = s;
Array.Sort(sorted_s);
for ( int i = 0; i < len; ++i) {
if (s[i] != sorted_s[i]) {
int chI = sorted_s[i] - 'a' ;
int last_occ = loccur[chI];
char temp = s[last_occ];
s[last_occ] = s[i];
s[i] = temp;
break ;
}
}
return String.Join( "" , s);
}
public static void Main(String[] args)
{
String s = "geeks" ;
Console.Write(findSmallest(s.ToCharArray()));
}
}
|
Javascript
<script>
function findSmallest(s)
{
let len = s.length;
let loccur = new Array(26);
loccur.fill(-1);
for (let i = len - 1; i >= 0; --i)
{
let chI = s[i].charCodeAt() -
'a' .charCodeAt();
if (loccur[chI] == -1)
{
loccur[chI] = i;
}
}
let sorted_s = s;
sorted_s.sort();
for (let i = 0; i < len; ++i)
{
if (s[i] != sorted_s[i])
{
let chI = sorted_s[i].charCodeAt() -
'a' .charCodeAt();
let last_occ = loccur[chI];
let temp = s[i];
s[i] = s[last_occ];
s[last_occ] = temp;
break ;
}
}
return s.join( "" );
}
let s = "geeks" ;
document.write(findSmallest(s.split( '' )));
</script>
|
Time Complexity: O(N*log(N))
Auxiliary Space: O(1)
Optimized Approach in O(N)
As we know lexicographical order evaluates from left to right and decides whether its order is smaller or bigger to the compared string.
So , we find the first element from the left that have smaller element on its right indexes of it and note the current index and last occurrence of smaller element. After knowing their indexes we simply swap them. to track whether swapping need to be done or not at end , we use a flag variable called found because in some cases like ‘aaaa’ swapping not requires.
now return the array that contains String characters after swapping if found = 1 or without swapping if found = 0 as a ‘String’.
implementation of above approach in java
in java Strings are immutable . so instead of swapping , we note the indexes and also elements. at last we replace both elements with opposite index.
C++
#include <cstring>
#include <iostream>
#include <string>
using namespace std;
string findSmallest(string s)
{
int len = s.length();
int loccur[26];
memset (loccur, -1, sizeof (loccur));
for ( int i = len - 1; i >= 0; i--) {
int ch = s[i] - 'a' ;
if (loccur[ch] == -1) {
loccur[ch] = i;
}
}
int found = 0, index1 = -1,
index2 = -1;
string c1 = "" , c2 = "" ;
for ( int i = 0; i < len; i++) {
if (i > 0 && s[i] == s[i - 1]) {
continue ;
}
int ch = s[i] - 'a' ;
if (loccur[ch] >= 0 && found == 0) {
int j = 0;
for (j = 0; j < ch; j++) {
if (loccur[j] >= 0
&& loccur[j] > loccur[ch]) {
found = 1;
index1 = i;
c1 = s[i];
index2 = loccur[j];
c2 = s[index2];
break ;
}
}
}
}
string res = "" ;
if (found == 1) {
for ( int i = 0; i < len; i++) {
if (i == index1) {
res += c2;
}
else if (i == index2) {
res += c1;
}
else {
res += s[i];
}
}
}
else {
res = s;
}
return res;
}
int main()
{
cout << findSmallest( "geeks" ) << endl;
return 0;
}
|
Java
import java.io.*;
import java.util.*;
class GFG {
static String findSmallest(String s)
{
int len = s.length();
int [] loccur = new int [ 26 ];
Arrays.fill(loccur, - 1 );
for ( int i = len - 1 ; i >= 0 ; i--) {
int ch = s.charAt(i) - 'a' ;
if (loccur[ch] == - 1 ) {
loccur[ch] = i;
}
}
int found = 0 , index1 = - 1 ,
index2 = - 1 ;
String c1 = "" , c2 = "" ;
for ( int i = 0 ; i < len; i++) {
if (i> 0 && s.charAt(i)==s.charAt(i- 1 )){
continue ;
}
int ch = ( int )(s.charAt(i) - 'a' );
if (loccur[ch] >= 0 && found == 0 ) {
int j = 0 ;
for (j = 0 ; j < ch; j++) {
if (loccur[j] >= 0 && loccur[j] > loccur[ch]) {
found = 1 ;
index1 = i;
c1 = "" + s.charAt(i);
index2 = loccur[j];
c2 = "" + s.charAt(index2);
break ;
}
}
}
}
String res = "" ;
if (found == 1 ) {
for ( int i = 0 ; i < len; i++) {
if (i == index1) {
res += c2;
}
else if (i == index2) {
res += c1;
}
else {
res += "" + s.charAt(i);
}
}
}
else {
for ( int i = 0 ; i < len; i++) {
res += "" + s.charAt(i);
}
}
return res;
}
public static void main(String[] args)
{
System.out.println(findSmallest( "geeks" ));
}
}
|
Python3
def find_smallest(s):
len_s = len (s)
loccur = [ - 1 ] * 26
for i in range (len_s - 1 , - 1 , - 1 ):
ch = ord (s[i]) - ord ( 'a' )
if loccur[ch] = = - 1 :
loccur[ch] = i
found, index1, index2 = 0 , - 1 , - 1
c1, c2 = " ", " "
for i in range (len_s):
if i > 0 and s[i] = = s[i - 1 ]:
continue
ch = ord (s[i]) - ord ( 'a' )
if loccur[ch] > = 0 and found = = 0 :
for j in range (ch):
if loccur[j] > = 0 and loccur[j] > loccur[ch]:
found = 1
index1 = i
c1 = s[i]
index2 = loccur[j]
c2 = s[index2]
break
res = ""
if found = = 1 :
for i in range (len_s):
if i = = index1:
res + = c2
elif i = = index2:
res + = c1
else :
res + = s[i]
else :
res = s
return res
print (find_smallest( "geeks" ))
|
C#
using System;
class Program
{
static string FindSmallest( string s)
{
int len = s.Length;
int [] loccur = new int [26];
Array.Fill(loccur, -1);
for ( int i = len - 1; i >= 0; i--)
{
int ch = s[i] - 'a' ;
if (loccur[ch] == -1)
{
loccur[ch] = i;
}
}
int found = 0, index1 = -1, index2 = -1;
char c1 = '\0' , c2 = '\0' ;
for ( int i = 0; i < len; i++)
{
if (i > 0 && s[i] == s[i - 1])
{
continue ;
}
int ch = s[i] - 'a' ;
if (loccur[ch] >= 0 && found == 0)
{
int j = 0;
for (j = 0; j < ch; j++)
{
if (loccur[j] >= 0 && loccur[j] > loccur[ch])
{
found = 1;
index1 = i;
c1 = s[i];
index2 = loccur[j];
c2 = s[index2];
break ;
}
}
}
}
string res = "" ;
if (found == 1)
{
for ( int i = 0; i < len; i++)
{
if (i == index1)
{
res += c2.ToString();
}
else if (i == index2)
{
res += c1.ToString();
}
else
{
res += s[i];
}
}
}
else
{
res = s;
}
return res;
}
static void Main()
{
Console.WriteLine(FindSmallest( "geeks" ));
}
}
|
Javascript
function findSmallest(s) {
let len = s.length;
let loccur = new Array(26).fill(-1);
for (let i = len - 1; i >= 0; i--) {
let ch = s.charCodeAt(i) - 'a' .charCodeAt(0);
if (loccur[ch] === -1) {
loccur[ch] = i;
}
}
let found = 0,
index1 = -1,
index2 = -1;
let c1 = "" ,
c2 = "" ;
for (let i = 0; i < len; i++) {
if (i > 0 && s.charAt(i) === s.charAt(i - 1)) {
continue ;
}
let ch = s.charCodeAt(i) - 'a' .charCodeAt(0);
if (loccur[ch] >= 0 && found === 0) {
let j = 0;
for (j = 0; j < ch; j++) {
if (loccur[j] >= 0 && loccur[j] > loccur[ch]) {
found = 1;
index1 = i;
c1 = s.charAt(i);
index2 = loccur[j];
c2 = s.charAt(index2);
break ;
}
}
}
}
let res = "" ;
if (found === 1) {
for (let i = 0; i < len; i++) {
if (i === index1) {
res += c2;
} else if (i === index2) {
res += c1;
} else {
res += s.charAt(i);
}
}
} else {
for (let i = 0; i < len; i++) {
res += s.charAt(i);
}
}
return res;
}
console.log(findSmallest( "geeks" ));
|
Output : eegks
Time Complexity :O(N).
Auxiliary Space : O(26) ~ O(1).
Like Article
Suggest improvement
Share your thoughts in the comments
Please Login to comment...