Open In App

Largest Number by One Swap

Last Updated : 23 Aug, 2025
Comments
Improve
Suggest changes
9 Likes
Like
Report

Given a numeric string s, find the lexicographically largest string by swapping at most one pair of characters.

Note:  Leading zeros are not allowed.

Examples: 

Input: s = "768"
Output: 867
Explanation: Swapping the 1st and 3rd characters (7 and 8 respectively), gives the lexicographically largest string.

Input: s = "333"
Output: 333
Explanation: Performing any swaps gives the same result i.e 333.

[Naive Approach] Tries all possible swaps - O(n^3) Time and O(1) Space

The idea is to try all possible single swaps of two digits and keeps track of the maximum number found.

C++
#include <iostream>
#include <string>
using namespace std;

string largestSwap(string &s) {
    string ans = s;

    // try swapping every pair
    for (int i = 0; i < s.size(); i++) {
        for (int j = i + 1; j < s.size(); j++) {
            swap(s[i], s[j]);
            ans = max(ans, s);
            
            // backtrack
            swap(s[i], s[j]);
        }
    }
    return ans;
}

int main() {
    string s = "768";
    cout << largestSwap(s) << "\n";
}
Java
class GfG {

    static String largestSwap(String s) {
        String ans = s;
        char[] arr = s.toCharArray();

        // try swapping every pair
        for (int i = 0; i < arr.length; i++) {
            for (int j = i + 1; j < arr.length; j++) {
                char tmp = arr[i];
                arr[i] = arr[j];
                arr[j] = tmp;

                String curr = new String(arr);
                if (curr.compareTo(ans) > 0) ans = curr;

                // backtrack
                arr[j] = arr[i];
                arr[i] = tmp;
            }
        }
        return ans;
    }

    public static void main(String[] args) {
        String s = "768";
        System.out.println(largestSwap(s));
    }
}
Python
def largestSwap(s):
    ans = s
    arr = list(s)

    # try swapping every pair
    for i in range(len(arr)):
        for j in range(i + 1, len(arr)):
            arr[i], arr[j] = arr[j], arr[i]
            curr = ''.join(arr)
            ans = max(ans, curr)
            
            # backtrack
            arr[i], arr[j] = arr[j], arr[i]  

    return ans

if __name__ == "__main__":
    s = "768"
    print(largestSwap(s))
C#
using System;

class GfG {
    
    static string largestSwap(string s) {
        string ans = s;
        char[] arr = s.ToCharArray();

        // try swapping every pair
        for (int i = 0; i < arr.Length; i++) {
            for (int j = i + 1; j < arr.Length; j++) {
                char tmp = arr[i];
                arr[i] = arr[j];
                arr[j] = tmp;

                string curr = new string(arr);
                if (String.Compare(curr, ans) > 0) ans = curr;

                // backtrack
                arr[j] = arr[i];
                arr[i] = tmp;
            }
        }
        return ans;
    }

    static void Main() {
        string s = "768";
        Console.WriteLine(largestSwap(s));
    }
}
JavaScript
function largestSwap(s) {
    let ans = s;
    let arr = s.split('');

    // try swapping every pair
    for (let i = 0; i < arr.length; i++) {
        for (let j = i + 1; j < arr.length; j++) {
            
            // copy original
            let tempArr = arr.slice(); 
            [tempArr[i], tempArr[j]] = [tempArr[j], tempArr[i]];
            let curr = tempArr.join('');
            if (curr > ans) ans = curr;
        }
    }

    return ans;
}

// Driver Code
let s = "768";
console.log(largestSwap(s));

Output
867

[Expected Approach] Greedy Rightmost Maximum Swap - O(n) Time and O(1) Space

Since only one swap is allowed, we should make the leftmost digit as large as possible.

So, while traversing from right to left, we keep track of the maximum digit seen so far. If we find a smaller digit before it, that’s our candidate for swapping. At the end, we swap the leftmost smaller digit with the rightmost largest digit.

This ensures the first position where the number can be improved is maximized. If no such swap exists, the number is already the largest.

Step By Step Implementations:

  • Traverse the string from right to left, keeping track of:
    -> maxDigit: the largest digit seen so far.
    -> maxIndx: its index.
  • If the current digit is smaller than maxDigit, mark it as a candidate for swapping (l, r).
    -> Since we go right-to-left, this ensures we pick the leftmost smaller digit with the best possible swap.
  • If no such pair is found, the number is already the largest.
  • Otherwise, perform the swap and return the new string.
C++
#include <iostream>
#include <string>
using namespace std;

string largestSwap(string &s) {
    char maxDigit = '0';
    int maxIndx = -1;
    int l = -1, r = -1;

    // Traverse from right to left
    for (int i = s.size() - 1; i >= 0; i--)
    {
        // Update maxDigit if current digit is larger
        if (s[i] > maxDigit)
        {
            maxDigit = s[i];
            maxIndx = i;
        }
        
        // Found a smaller digit before a larger one
        else if (s[i] < maxDigit)
        {
            l = i;
            r = maxIndx;
        }
    }

    // If no swap needed, return original
    if (l == -1) return s;

    // Perform swap
    swap(s[l], s[r]);
    
    return s;
}

int main() {
    string s = "768";
    cout << largestSwap(s) << endl;
}
Java
class GfG {
    static String largestSwap(String s) {
        char[] arr = s.toCharArray();
        char maxDigit = '0';
        int maxIndx = -1, l = -1, r = -1;

        // Traverse from right to left
        for (int i = arr.length - 1; i >= 0; i--) {
            
            // Update maxDigit if current digit is larger
            if (arr[i] > maxDigit) {
                maxDigit = arr[i];
                maxIndx = i;
            }
            // Found a smaller digit before a larger one
            else if (arr[i] < maxDigit) {
                l = i;
                r = maxIndx;
            }
        }

        // If no swap needed, return original
        if (l == -1) return s;

        // Perform swap
        char temp = arr[l];
        arr[l] = arr[r];
        arr[r] = temp;

        return new String(arr);
    }

    public static void main(String[] args) {
        String s = "768";
        System.out.println(largestSwap(s));
    }
}
Python
def largestSwap(s):
    arr = list(s)
    maxDigit = '0'
    maxIndx, l, r = -1, -1, -1

    # Traverse from right to left
    for i in range(len(arr) - 1, -1, -1):
        if arr[i] > maxDigit:
            maxDigit = arr[i]
            maxIndx = i
        elif arr[i] < maxDigit:
            l, r = i, maxIndx

    if l == -1:
        return s

    # Perform swap
    arr[l], arr[r] = arr[r], arr[l]
    return "".join(arr)


if __name__ == "__main__":
    s = "768"
    print(largestSwap(s))
C#
using System;

class GfG {
    static string largestSwap(string s) {
        char[] arr = s.ToCharArray();
        char maxDigit = '0';
        int maxIndx = -1, l = -1, r = -1;

        // Traverse from right to left
        for (int i = arr.Length - 1; i >= 0; i--) {
          
            // Update maxDigit if current digit is larger
            if (arr[i] > maxDigit) {
                maxDigit = arr[i];
                maxIndx = i;
            }
            
            // Found a smaller digit before a larger one
            else if (arr[i] < maxDigit) {
                l = i;
                r = maxIndx;
            }
        }

        // If no swap needed, return original
        if (l == -1) return s;

        // Perform swap
        char temp = arr[l];
        arr[l] = arr[r];
        arr[r] = temp;

        return new string(arr);
    }

    static void Main() {
        string s = "768";
        Console.WriteLine(largestSwap(s));
    }
}
JavaScript
function largestSwap(s) {
    let arr = s.split('');
    let maxDigit = '0';
    let maxIndx = -1, l = -1, r = -1;

    // Traverse from right to left
    for (let i = arr.length - 1; i >= 0; i--) {
        
        // Update maxDigit if current digit is larger
        if (arr[i] > maxDigit) {
            maxDigit = arr[i];
            maxIndx = i;
        }
        
        // Found a smaller digit before a larger one
        else if (arr[i] < maxDigit) {
            l = i;
            r = maxIndx;
        }
    }

    // If no swap needed, return original
    if (l === -1) return s;

    // Perform swap
    [arr[l], arr[r]] = [arr[r], arr[l]];
    return arr.join('');
}

// Driver Code
let s = "768";
console.log(largestSwap(s));

Output
867

Explore