- Related Questions & Answers
- Program to check whether two string arrays are equivalent or not in Python
- Java Program to check whether two Strings are an anagram or not.
- Check whether the given numbers are Cousin prime or not in Python
- Check if two strings are equal or not in Arduino
- Check whether triangle is valid or not if sides are given in Python
- C Program to check if two strings are same or not
- Program to check whether given words are maintaining given pattern or not in C++
- Program to check two strings are 0 or 1 edit distance away or not in Python
- Program to check whether parentheses are balanced or not in Python
- C# program to check whether two sequences are the same or not
- Program to check whether leaves sequences are same of two leaves or not in python
- Check whether two strings are anagram of each other in Python
- Program to check whether given graph is bipartite or not in Python
- Program to check whether given password meets criteria or not in Python
- Program to check whether final string can be formed using other two strings or not in Python

- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who

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 −

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"

True

Advertisements