Lexicographically largest string possible in one swap - GeeksforGeeks

03 Aug, 2021
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++
Java
Python3
C#
Javascript
// C++ implementation to find the// lexicographically largest string// by atmost at most one swap #include <bits/stdc++.h>using namespace std; // Function to return the// lexicographically largest// string possible by swapping// at most one characterstring findLargest(string s){    int len = s.size();     // Stores last occurrence    // of every character    int loccur[26];     // Initialize with -1 for    // every character    memset(loccur, -1, sizeof(loccur));     for (int i = len - 1; i >= 0; --i) {         // Keep updating the last        // occurrence of each character        int chI = s[i] - 'a';        // If a previously unvisited        // character occurs        if (loccur[chI] == -1) {            loccur[chI] = i;        }    }    // Stores the sorted string    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]) {             // 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 Programint main(){    string s = "yrstvw";    cout << findLargest(s);    return 0;}
// Java implementation to find the// lexicographically largest string// by atmost at most one swapimport java.util.*;import java.lang.*; class GFG{     // Function to return the// lexicographically largest// string possible by swapping// at most one characterstatic String findLargest(StringBuilder s){    int len = s.length();         // Stores last occurrence    // of every character    int[] loccur = new int[26];         // Initialize with -1 for    // every character    Arrays.fill(loccur, -1);         for(int i = len - 1; i >= 0; --i)    {                 // Keep updating the last        // occurrence of each character        int chI = s.charAt(i) - 'a';                 // If a previously unvisited        // character occurs        if (loccur[chI] == -1)        {            loccur[chI] = i;        }    }         // Stores the sorted string    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])        {                         // 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 tmp = s.charAt(i);            s.setCharAt(i, s.charAt(last_occ));            s.setCharAt(last_occ, tmp);                         break;        }    }    return s.toString();} // Function to reverse arraystatic 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;    }} // Driver Codepublic static void main(String[] args){    StringBuilder s = new StringBuilder("yrstvw");         System.out.println(findLargest(s));}} // This code is contributed by offbeat
# Python3 implementation to find the # lexicographically largest string # by atmost at most one swap # Function to return the # lexicographically largest # string possible by swapping # at most one characterdef findLargest(s):    Len = len(s)     # Stores last occurrence     # of every character    # Initialize with -1 for     # every character    loccur = [-1 for i in range(26)]     for i in range(Len - 1, -1, -1):         # Keep updating the last         # occurrence of each character        chI = ord(s[i]) - ord('a')         # If a previously unvisited         # character occurs        if(loccur[chI] == -1):            loccur[chI] = i         # Stores the sorted string    sorted_s = sorted(s, reverse = True)    for i in range(Len):        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]            temp = list(s)             # Swap this with the last             # occurrence            temp[i], temp[last_occ] = (temp[last_occ],                                       temp[i])            s = "".join(temp)            break    return s # Driver codes = "yrstvw"print(findLargest(s)) # This code is contributed by avanitrachhadiya2155
// C# implementation to find the// lexicographically largest string// by atmost at most one swapusing System;using System.Collections.Generic; class GFG{     // Function to return the// lexicographically largest// string possible by swapping// at most one characterstatic string findLargest(char[] s){    int len = s.Length;          // Stores last occurrence    // of every character    int[] loccur = new int[26];          // Initialize with -1 for    // every character    Array.Fill(loccur, -1);          for(int i = len - 1; i >= 0; --i)    {                 // Keep updating the last        // occurrence of each character        int chI = s[i] - 'a';                  // If a previously unvisited        // character occurs        if (loccur[chI] == -1)        {            loccur[chI] = i;        }    }          // Stores the sorted string    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])        {                         // 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[i];            s[i] = s[last_occ];            s[last_occ] = temp;            break;        }    }    return (new string(s));} // Driver Codestatic void Main(){    string str = "yrstvw";    char[] s = str.ToCharArray();         Console.WriteLine(findLargest(s));}} // This code is contributed by divyesh072019
<script>     // Javascript implementation to find the    // lexicographically largest string    // by atmost at most one swap         // Function to return the    // lexicographically largest    // string possible by swapping    // at most one character    function findLargest(s)    {        let len = s.length;         // Stores last occurrence        // of every character        let loccur = new Array(26);         // Initialize with -1 for        // every character        loccur.fill(-1);         for(let i = len - 1; i >= 0; --i)        {             // Keep updating the last            // occurrence of each character            let chI = s[i].charCodeAt() - 'a'.charCodeAt();             // If a previously unvisited            // character occurs            if (loccur[chI] == -1)            {                loccur[chI] = i;            }        }         // Stores the sorted string        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])            {                 // 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(""));    }         let str = "yrstvw";    let s = str.split('');          document.write(findLargest(s));     </script>
ywstvr
 
offbeat
avanitrachhadiya2155
divyesh072019
mukesh07
sagartomar9927
lexicographic-ordering
Swap-Program
Competitive Programming
Greedy
Sorting
Strings
Strings
Greedy
Sorting
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Multistage Graph (Shortest Path)
Breadth First Traversal ( BFS ) on a 2D array
Difference between Backtracking and Branch-N-Bound technique
Minimum changes required to make all Array elements Prime
Most important type of Algorithms
Dijkstra's shortest path algorithm | Greedy Algo-7
Kruskal’s Minimum Spanning Tree Algorithm | Greedy Algo-2
Prim’s Minimum Spanning Tree (MST) | Greedy Algo-5
Program for array rotation
Huffman Coding | Greedy Algo-3