Skip to content
Related Articles

Related Articles

Improve Article

Lexicographically largest string possible in one swap

  • Difficulty Level : Hard
  • Last Updated : 13 Apr, 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++




// 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 character
string 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 Program
int main()
{
    string s = "yrstvw";
    cout << findLargest(s);
    return 0;
}

Java




// Java implementation to find the
// lexicographically largest string
// by atmost at most one swap
import java.util.*;
import java.lang.*;
 
class GFG{
     
// Function to return the
// lexicographically largest
// string possible by swapping
// at most one character
static 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();
}
 
// Funtion to reverse array
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;
    }
}
 
// Driver Code
public static void main(String[] args)
{
    StringBuilder s = new StringBuilder("yrstvw");
     
    System.out.println(findLargest(s));
}
}
 
// This code is contributed by offbeat

Python3




# 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 character
def 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 code
s = "yrstvw"
print(findLargest(s))
 
# This code is contributed by avanitrachhadiya2155

C#




// C# implementation to find the
// lexicographically largest string
// by atmost at most one swap
using System;
using System.Collections.Generic;
 
class GFG{
     
// Function to return the
// lexicographically largest
// string possible by swapping
// at most one character
static 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 Code
static void Main()
{
    string str = "yrstvw";
    char[] s = str.ToCharArray();
     
    Console.WriteLine(findLargest(s));
}
}
 
// This code is contributed by divyesh072019

Javascript




<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>
Output: 
ywstvr

 

Attention reader! Don’t stop learning now. Get hold of all the important DSA concepts with the DSA Self Paced Course at a student-friendly price and become industry ready.  To complete your preparation from learning a language to DS Algo and many more,  please refer Complete Interview Preparation Course.

In case you wish to attend live classes with experts, please refer DSA Live Classes for Working Professionals and Competitive Programming Live for Students.




My Personal Notes arrow_drop_up
Recommended Articles
Page :