Open In App

Find lexicographically smallest string in at most one swaps

Improve
Improve
Like Article
Like
Save
Share
Report

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>


Output

eegks








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 = # 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).



Last Updated : 15 Jan, 2024
Like Article
Save Article
Previous
Next
Share your thoughts in the comments
Similar Reads