Lexicographically largest string possible in one swap
Given string str of length N, the task is to obtain the lexicographically largest string by at most one swap.
Note: The swapping characters might not be adjacent.
Examples:
Input: str = “string”
Output: tsring
Explanation:
Lexicographically largest string obtained by swapping string -> tsring.
Input: str = “zyxw”
Output: zyxw
Explanation:
The given string is already lexicographically largest
Approach:
To solve the above-mentioned problem, the main idea is to use Sorting and compute the largest lexicographical string possible for the given string. After sorting the given string in descending order, find the first unmatched character from the given string and replace it with the last occurrence of the unmatched character in the sorted string.
Illustration:
str = “geeks”
Sorted string in descending order = “skgee”.
The first unmatched character is in the first place. This character needs to be swapped with the character at this position in the sorted string which results in the lexicographically largest string. On replacing “g” with the “s”, the string obtained is “seekg” which is lexicographically largest after one swap.
Below is the implementation of the above approach:
C++
#include <bits/stdc++.h>
using namespace std;
string findLargest(string s)
{
int len = s.size();
int loccur[26];
memset (loccur, -1, sizeof (loccur));
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(),
greater< int >());
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 = "yrstvw" ;
cout << findLargest(s);
return 0;
}
|
Java
import java.util.*;
import java.lang.*;
class GFG{
static String findLargest(StringBuilder 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.charAt(i) - 'a' ;
if (loccur[chI] == - 1 )
{
loccur[chI] = i;
}
}
char [] sorted_s = s.toString().toCharArray();
Arrays.sort(sorted_s);
reverse(sorted_s);
for ( int i = 0 ; i < len; ++i)
{
if (s.charAt(i) != sorted_s[i])
{
int chI = sorted_s[i] - 'a' ;
int last_occ = loccur[chI];
char tmp = s.charAt(i);
s.setCharAt(i, s.charAt(last_occ));
s.setCharAt(last_occ, tmp);
break ;
}
}
return s.toString();
}
static void reverse( char a[])
{
int i, n = a.length;
for (i = 0 ; i < n / 2 ; i++)
{
char t = a[i];
a[i] = a[n - i - 1 ];
a[n - i - 1 ] = t;
}
}
public static void main(String[] args)
{
StringBuilder s = new StringBuilder( "yrstvw" );
System.out.println(findLargest(s));
}
}
|
Python3
def findLargest(s):
Len = len (s)
loccur = [ - 1 for i in range ( 26 )]
for i in range ( Len - 1 , - 1 , - 1 ):
chI = ord (s[i]) - ord ( 'a' )
if (loccur[chI] = = - 1 ):
loccur[chI] = i
sorted_s = sorted (s, reverse = True )
for i in range ( Len ):
if (s[i] ! = sorted_s[i]):
chI = ( ord (sorted_s[i]) -
ord ( 'a' ))
last_occ = loccur[chI]
temp = list (s)
temp[i], temp[last_occ] = (temp[last_occ],
temp[i])
s = "".join(temp)
break
return s
s = "yrstvw"
print (findLargest(s))
|
C#
using System;
using System.Collections.Generic;
class GFG{
static string findLargest( char [] s)
{
int len = s.Length;
int [] loccur = new int [26];
Array.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 = ( new string (s)).ToCharArray();
Array.Sort(sorted_s);
Array.Reverse(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[i];
s[i] = s[last_occ];
s[last_occ] = temp;
break ;
}
}
return ( new string (s));
}
static void Main()
{
string str = "yrstvw" ;
char [] s = str.ToCharArray();
Console.WriteLine(findLargest(s));
}
}
|
Javascript
<script>
function findLargest(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.join( "" ).split( '' );
sorted_s.sort();
sorted_s.reverse();
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 str = "yrstvw" ;
let s = str.split( '' );
document.write(findLargest(s));
</script>
|
Time Complexity: O(n * log(n)), where n is the length of the given string.
Auxiliary Space: O(26) ? O(1), no extra space is required, so it is a constant.
Last Updated :
02 Jan, 2023
Like Article
Save Article
Share your thoughts in the comments
Please Login to comment...