VOOZH about

URL: https://www.geeksforgeeks.org/dsa/form-smallest-number-using-one-swap-operation/

⇱ Smallest Number Possible by At Most One Swap - GeeksforGeeks


  • Courses
  • Tutorials
  • Interview Prep

Smallest Number Possible by At Most One Swap

Last Updated : 10 Jun, 2026

Given a non-negative integer represented as a string s, find the smallest possible number that can be obtained by performing at most one swap of two digits.
Note: Output should not contain leading zeros.

Examples:

Input: s = "9625635"
Output: "2695635"
Explanation: Swapped the digits 9 and 2.

Input: s = "1205763"
Output: "1025763"
Explanation: Swapped the digits 0 and 2.

[Naive Approach] Try Every Swap - O(n³) Time and O(1) Space

Since only one swap is allowed, try swapping every pair of digits and generate all possible valid numbers. Among all numbers obtained after at most one swap, keep track of the smallest one and return it. This guarantees finding the minimum possible number.


Output
2695635

[Expected Approach] Greedy Swapping with Right-Side Minimum Digits - O(n) Time and O(n) Space

Since only one swap is allowed, the leftmost digit has the highest impact on the value of the number, so we try to make the leftmost possible position as small as possible.

We greedily reduce the leftmost possible digit. First, try to improve the leading digit using the smallest non-zero digit on its right. Otherwise, find the next leftmost position that can be improved.

Step-by-step Implementation:

  • Store the index of the smallest digit available on the right of every position.
  • Try to reduce the leading digit by swapping it with the smallest non-zero digit on its right.
  • If such a swap exists, perform it and return the result.
  • Otherwise, scan from left to right and find the first position that can be improved.
  • Swap it with the smallest digit available on its right.
  • Return the resulting string.

Output
2695635
Comment
Article Tags: