Check whether two strings are equivalent or not according to given condition in Python

PythonServer Side ProgrammingProgramming

Suppose we have two strings s and t of same size. We have to check whether s and t are equivalent or not. There are few conditions to check:

  • They both are equal. Or,
  • If we divide the s into two contiguous substrings of same size and the substrings are s1 and s2 and also divide t same like, s into t1 and t2, then one of the following should be valid:
    • s1 is recursively equivalent to t1 and s2 is recursively equivalent to t2
    • s1 is recursively equivalent to t2 and s2 is recursively equivalent to t1

So, if the input is like s = "ppqp" t = "pqpp", then the output will be True as if we divide s and t into two parts s1 = "pp", s2 = "qp" and t1 = "pq", t2 = "pp", here s1 = t2 and if we divide s2 and t1 into two parts s21 = "q", s22 = "p", t11 = "p", t12 = "q", here also s21 = t12 and s22 = t11, so they are recursively equivalent.

To solve this, we will follow these steps −

  • Define a function util() . This will take s
  • if size of s is odd, then
    • return s
  • left := util(left half part of s)
  • right := util(right half part of s)
  • return minimum of (left concatenate right), (right concatenate left)
  • From the main method return true when util(s) is same as util(t) otherwise false

Let us see the following implementation to get better understanding −

Example Code

Live Demo

def util(s):
   if len(s) & 1 != 0:
      return s
   left = util(s[0:int(len(s) / 2)])
   right = util(s[int(len(s) / 2):len(s)])
   return min(left + right, right + left)
def solve(s,t):
   return util(s) == util(t)

s = "ppqp"
t = "pqpp"
print(solve(s, t))


"ppqp", "pqpp"


Published on 16-Jan-2021 09:39:48