Program to find Lexicographically Smallest String With One Swap in Python

Suppose we have a string s, we have to find the lexicographically smallest string that can be made if we can make at most one swap between two characters in the given string s.

So, if the input is like "zyzx", then the output will be "xyzz"

To solve this, we will follow these steps −

  • temp := an array of size s and fill with 0
  • m:= size of s - 1
  • for i in range size of s -1 to -1, decrease by 1, do
    • if s[i] < s[m], then
      • m := i
    • temp[i] := m
    • for i in range 0 to size of s, do
      • a := temp[i]
      • if s[a] is not same as s[i], then
        • return substring of s [from index 0 to i] concatenate s[a] concatenate substring of s [from index i+1 to a] concatenate s[i] concatenate substring of s [from index a+1 to end]
  • return s


 Live Demo

class Solution:
   def solve(self, s):
      temp = [0]*len(s)
      for i in range(len(s)-1, -1, -1):
         if s[i]<s[m]: m=i
            temp[i] = m
      for i in range(len(s)):
         a = temp[i]
         if s[a] != s[i]:
            return s[:i]+s[a]+s[i+1:a]+s[i]+s[a+1:]
      return s
ob = Solution()





Updated on: 06-Oct-2020

2K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started