Program to check is there any permutation that is lexicographically bigger or not between two strings in Python


Suppose we have two strings s and t of the same size, we have to check whether there is some permutation of s, say s1, and permutation of t, say t1, such that: s1[i] ≤ t1[i] for all 0 ≤ i < n or t1[i] ≤ s1[i] for all 0 ≤ i < n.

So, if the input is like s = "vyx" t = "wzx", then the output will be True, as we can have s1 = "vxy" and t1 = "wxz".

To solve this, we will follow these steps −

  • if s and t are empty, then
    • return True
  • s := sort the string s
  • t := sort the string t
  • Define a function util() . This will take s1, s2
  • for i in range 0 to size of s1, do
    • if s1[i] > t1[i], then
      • return False
  • return True
  • From the main method do the following −
  • if util(s, t) is true, then
    • return True
  • swap s and t
  • return util(s, t)

Let us see the following implementation to get better understanding −

Example

 Live Demo

class Solution:
   def solve(self, s, t):
      if not len(s) or not len(t):
         return True
         s = sorted(s)
         t = sorted(t)
   def util(s1, t1):
      for i in range(len(s1)):
         if s1[i] > t1[i]:
            return False
         return True
         if util(s, t):
            return True
      s, t = t, s
      return util(s, t)
ob = Solution()
s = "vyx"
t = "wzx"
print(ob.solve(s, t))

Input

"vyx", "wzx"

Output

True

Updated on: 19-Nov-2020

68 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements