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++
// C++ implementation of the above approach
#include <bits/stdc++.h>
using namespace std;
// Function to return the lexicographically
// smallest string that can be formed by
// swapping at most one character.
// The characters might not necessarily
// be adjacent.
string findSmallest(string s)
{
int len = s.size();
// Store last occurrence of every character
// and set -1 as default for every character.
vector<int> loccur(26,-1);
for (int i = len - 1; i >= 0; --i) {
// Character index to fill
// in the last occurrence array
int chI = s[i] - 'a';
if (loccur[chI] == -1) {
// If this is true then this
// character is being visited
// for the first time from the last
// Thus last occurrence of this
// character is stored in this index
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]) {
// Character to replace
int chI = sorted_s[i] - 'a';
// Find the last occurrence
// of this character.
int last_occ = loccur[chI];
// Swap this with the last occurrence
swap(s[i], s[last_occ]);
break;
}
}
return s;
}
// Driver code
int main()
{
string s = "geeks";
cout << findSmallest(s);
return 0;
}
Java
// Java implementation of the above approach
import java.util.*;
class GFG{
// Function to return the lexicographically
// smallest String that can be formed by
// swapping at most one character.
// The characters might not necessarily
// be adjacent.
static String findSmallest(char []s)
{
int len = s.length;
// Store last occurrence of every character
int []loccur = new int[26];
// Set -1 as default for every character.
Arrays.fill(loccur, -1);
for (int i = len - 1; i >= 0; --i) {
// Character index to fill
// in the last occurrence array
int chI = s[i] - 'a';
if (loccur[chI] == -1) {
// If this is true then this
// character is being visited
// for the first time from the last
// Thus last occurrence of this
// character is stored in this index
loccur[chI] = i;
}
}
char []sorted_s = s;
Arrays.sort(sorted_s);
for (int i = 0; i < len; ++i) {
if (s[i] != sorted_s[i]) {
// Character to replace
int chI = sorted_s[i] - 'a';
// Find the last occurrence
// of this character.
int last_occ = loccur[chI];
// Swap this with the last occurrence
char temp = s[last_occ];
s[last_occ] = s[i];
s[i] = temp;
break;
}
}
return String.valueOf(s);
}
// Driver code
public static void main(String[] args)
{
String s = "geeks";
System.out.print(findSmallest(s.toCharArray()));
}
}
// This code is contributed by 29AjayKumar
Python3
# Python3 implementation of the above approach
# Function to return the lexicographically
# smallest string that can be formed by
# swapping at most one character.
# The characters might not necessarily
# be adjacent.
def findSmallest(s) :
length = len(s);
# Store last occurrence of every character
# Set -1 as default for every character.
loccur = [-1]*26;
for i in range(length - 1, -1, -1) :
# Character index to fill
# in the last occurrence array
chI = ord(s[i]) - ord('a');
if (loccur[chI] == -1) :
# If this is true then this
# character is being visited
# for the first time from the last
# Thus last occurrence of this
# character is stored in this index
loccur[chI] = i;
sorted_s = s;
sorted_s.sort();
for i in range(length) :
if (s[i] != sorted_s[i]) :
# Character to replace
chI = ord(sorted_s[i]) - ord('a');
# Find the last occurrence
# of this character.
last_occ = loccur[chI];
# Swap this with the last occurrence
# swap(s[i], s[last_occ]);
s[i],s[last_occ] = s[last_occ],s[i]
break;
return "".join(s);
# Driver code
if __name__ == "__main__" :
s = "geeks";
print(findSmallest(list(s)));
# This code is contributed by Yash_R
C#
// C# implementation of the above approach
using System;
class GFG{
// Function to return the lexicographically
// smallest String that can be formed by
// swapping at most one character.
// The characters might not necessarily
// be adjacent.
static String findSmallest(char []s)
{
int len = s.Length;
// Store last occurrence of every character
int []loccur = new int[26];
// Set -1 as default for every character.
for (int i = 0; i < 26; i++)
loccur[i] = -1;
for (int i = len - 1; i >= 0; --i) {
// char index to fill
// in the last occurrence array
int chI = s[i] - 'a';
if (loccur[chI] == -1) {
// If this is true then this
// character is being visited
// for the first time from the last
// Thus last occurrence of this
// character is stored in this index
loccur[chI] = i;
}
}
char []sorted_s = s;
Array.Sort(sorted_s);
for (int i = 0; i < len; ++i) {
if (s[i] != sorted_s[i]) {
// char to replace
int chI = sorted_s[i] - 'a';
// Find the last occurrence
// of this character.
int last_occ = loccur[chI];
// Swap this with the last occurrence
char temp = s[last_occ];
s[last_occ] = s[i];
s[i] = temp;
break;
}
}
return String.Join("", s);
}
// Driver code
public static void Main(String[] args)
{
String s = "geeks";
Console.Write(findSmallest(s.ToCharArray()));
}
}
// This code is contributed by sapnasingh4991
JavaScript
<script>
// Javascript implementation of the above approach
// Function to return the lexicographically
// smallest string that can be formed by
// swapping at most one character.
// The characters might not necessarily
// be adjacent.
function findSmallest(s)
{
let len = s.length;
// Store last occurrence of every character
let loccur = new Array(26);
// Set -1 as default for every character.
loccur.fill(-1);
for(let i = len - 1; i >= 0; --i)
{
// Character index to fill
// in the last occurrence array
let chI = s[i].charCodeAt() -
'a'.charCodeAt();
if (loccur[chI] == -1)
{
// If this is true then this
// character is being visited
// for the first time from the last
// Thus last occurrence of this
// character is stored in this index
loccur[chI] = i;
}
}
let sorted_s = s;
sorted_s.sort();
for(let i = 0; i < len; ++i)
{
if (s[i] != sorted_s[i])
{
// Character to replace
let chI = sorted_s[i].charCodeAt() -
'a'.charCodeAt();
// Find the last occurrence
// of this character.
let last_occ = loccur[chI];
// Swap this with the last occurrence
let temp = s[i];
s[i] = s[last_occ];
s[last_occ] = temp;
break;
}
}
return s.join("");
}
// Driver code
let s = "geeks";
document.write(findSmallest(s.split('')));
// This code is contributed by vaibhavrabadiya3
</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();
// Used to track last occurrences
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; // Tracks the indexes
string c1 = "", c2 = ""; // Tracks the elements
for (int i = 0; i < len; i++) {
if (i > 0 && s[i] == s[i - 1]) {
continue; // Eliminates continuously repeated
// elements
}
int ch = s[i] - 'a';
if (loccur[ch] >= 0 && found == 0) {
int j = 0;
for (j = 0; j < ch; j++) {
// If loop will be executed when smaller
// element on the right of the current
// position is found
if (loccur[j] >= 0
&& loccur[j] > loccur[ch]) {
found = 1;
index1 = i; // Note the current element
// index
c1 = s[i]; // and current element
index2 = loccur[j];
c2 = s[index2]; // Last occurrence of
// the smaller element
break;
}
}
}
}
string res = "";
if (found == 1) { // Perform swapping 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; // Result
}
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();
// used to track last occurrences
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; // tracks the indexes
String c1 = "", c2 = ""; // tracks the elements
for (int i = 0; i < len; i++) {
if(i>0 && s.charAt(i)==s.charAt(i-1)){
continue; // eliminates continuously repeated elements
}
int ch = (int)(s.charAt(i) - 'a');
if (loccur[ch] >= 0 && found == 0) {
int j = 0;
for (j = 0; j < ch; j++) {
// if loop will be executed when smaller
// element on right of current position
// is found
if (loccur[j] >= 0 && loccur[j] > loccur[ch]) {
found = 1;
index1 = i; // note the current element index
c1 = "" + s.charAt(i); // and current element
index2 = loccur[j];
c2 = "" + s.charAt(index2); // last occurrence of smaller element
break;
}
}
}
}
String res = "";
if (found == 1) { // perform swapping 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; // result
}
public static void main(String[] args)
{
System.out.println(findSmallest("geeks"));
}
}
Python3
def find_smallest(s):
len_s = len(s)
# Used to track last occurrences
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 # Tracks the indexes
c1, c2 = "", "" # Tracks the elements
for i in range(len_s):
if i > 0 and s[i] == s[i - 1]:
continue # Eliminates continuously repeated elements
ch = ord(s[i]) - ord('a')
if loccur[ch] >= 0 and found == 0:
for j in range(ch):
# If loop will be executed when a smaller
# element on the right of the current
# position is found
if loccur[j] >= 0 and loccur[j] > loccur[ch]:
found = 1
index1 = i # Note the current element index
c1 = s[i] # and current element
index2 = loccur[j]
c2 = s[index2] # Last occurrence of
# the smaller element
break
res = ""
if found == 1: # Perform swapping 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 # Result
# Driver Code
print(find_smallest("geeks"))
# This code is contributed by Dwaipayan Bandyopadhyay
C#
using System;
class Program
{
static string FindSmallest(string s)
{
int len = s.Length;
// Used to track last occurrences
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; // Tracks the indexes
char c1 = '\0', c2 = '\0'; // Tracks the elements
for (int i = 0; i < len; i++)
{
if (i > 0 && s[i] == s[i - 1])
{
continue; // Eliminates continuously repeated elements
}
int ch = s[i] - 'a';
if (loccur[ch] >= 0 && found == 0)
{
int j = 0;
for (j = 0; j < ch; j++)
{
// If loop will be executed when a smaller
// element on the right of the current
// position is found
if (loccur[j] >= 0 && loccur[j] > loccur[ch])
{
found = 1;
index1 = i; // Note the current element index
c1 = s[i]; // and current element
index2 = loccur[j];
c2 = s[index2]; // Last occurrence of the smaller element
break;
}
}
}
}
string res = "";
if (found == 1)
{
// Perform swapping 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; // Result
}
static void Main()
{
Console.WriteLine(FindSmallest("geeks"));
}
}
JavaScript
function findSmallest(s) {
let len = s.length;
// used to track last occurrences
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; // tracks the indexes
let c1 = "",
c2 = ""; // tracks the elements
for (let i = 0; i < len; i++) {
if (i > 0 && s.charAt(i) === s.charAt(i - 1)) {
continue; // eliminates continuously repeated elements
}
let ch = s.charCodeAt(i) - 'a'.charCodeAt(0);
if (loccur[ch] >= 0 && found === 0) {
let j = 0;
for (j = 0; j < ch; j++) {
// if loop will be executed when smaller
// element on right of current position
// is found
if (loccur[j] >= 0 && loccur[j] > loccur[ch]) {
found = 1;
index1 = i; // note the current element index
c1 = s.charAt(i); // and current element
index2 = loccur[j];
c2 = s.charAt(index2); // last occurrence of smaller element
break;
}
}
}
}
let res = "";
if (found === 1) {
// perform swapping 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; // result
}
console.log(findSmallest("geeks"));
Output : eegks
Time Complexity :O(N).
Auxiliary Space : O(26) ~ O(1).
Similar Reads
Find Lexicographically smallest String
Given a circular string s, find whether there exists a permutation of s which is a K-periodic circular string and if it exists then find the lexicographically smallest permutation of s which is a K-periodic circular string. Return an empty string if there does not exist a valid permutation of s whic
6 min read
Lexicographically smaller string by swapping at most one character pair
Given two strings A and B of all uppercase letters, the task is to find whether is it possible to make string A strictly lexicographically smaller than string B by swapping at most one pair of characters in A.Examples: Input: A = "AGAIN", B = "ACTION" Output: Yes Explanation: We can make string A st
8 min read
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
Find Mth lexicographically smallest Binary String with no two adjacent 1
Given two integers N and M, the task is to find the Mth lexicographically smallest binary string (have only characters 1 and 0) of length N where there cannot be two consecutive 1s. Examples: Input: N = 2, M = 3.Output: 10Explanation: The only strings that can be made of size 2 are ["00", "01", "10"
6 min read
Lexicographically smallest Binary String formed using infinite swaps
Given a binary string s of length N, the task is to find the lexicographically smallest string using infinite number of swaps between 0's and 1's. Examples: Input: s = "1001001"Output: 0000111Explanation: Lexicographically smallest string of 1001001 is only 0000111 Input: s = "0001"Output: 0001Expla
8 min read
Lexicographically smallest String by pair swapping
Suppose you are given a string Str of length N and a set of Pairs ( i, j such that 0 <= i < j < N, 0 based indexing). Pair âi, jâ means that you can swap the ith and jth characters in the string any number of times. You have to output the lexicographically smallest string that can be produc
11 min read
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. In
7 min read
Find Lexicographically smallest String with Prefix Reversal
Given a string str of length N. You have to choose a non-zero integer K (K <= N), such that in one operation you can take the prefix of the string of length K and append the reverse of it to itself, the task is to find the lexicographically smallest string you can get. Examples: Input: str = "bvd
5 min read
Lexicographically smallest String by moving one Subsequence to the end
Given a string S of size N, having lowercase alphabets, the task is to find the lexicographically minimum string after moving a subsequence to the end of the string only once. Example: Input: N = 3, S = "asa" Output: aasExplanation: The optimal subsequence is "s". Removed, and added at last. Hence t
9 min read
Find the lexicographically smallest string which satisfies the given condition
Given an array, arr[] of N integers, where arr[i] represents the number of distinct characters in the prefix of length (i + 1) of a string S. The task is to find the lexicographically smallest string (if any exists) that satisfies the given prefix array. The string should be of lowercase English alp
10 min read