Groups of Special-Equivalent Strings in Python

PythonServer Side ProgrammingProgramming

Suppose we have an array of strings called A. One move onto S consists of swapping any two even indexed characters of S, or any two odd indexed characters of S.

Now, two strings S and T are special-equivalent if after any number of moves onto S, S is same as T. So, if S = "zzxy" and T = "xyzz" are special-equivalent because we may make the moves like "zzxy" to "xzzy" to "xyzz" that swap S[0] and S[2], then S[1] and S[3].

Now, a group of special-equivalent strings from A is a non-empty subset of A such that −

In every pair of strings in the group are special equivalent, and the group is the largest size possible (there is not a string S not in the group such that S is special equivalent to every string in that group) We have to find the number of groups of special-equivalent strings from A.

So, if the input is like ["abcd","cdab","cbad","xyzz","zzxy","zzyx"], then the output will be 3, as one group is ["abcd", "cdab", "cbad"], since they are all pairwise special equivalent, and none of the other strings are all pairwise special equivalent to these. There are also two other groups. These are ["xyzz", "zzxy"] and ["zzyx"].

To solve this, we will follow these steps −

  • codes := a new set
  • for each word in A, do
    • code := concatenate two strings with even position indices and another string with odd position indices
    • add code into codes
  • return size of codes

Let us see the following implementation to get better understanding −


 Live Demo

class Solution:
   def numSpecialEquivGroups(self, A):
      codes = set()
      for word in A:
         code = ''.join(sorted(word[::2])) +''.join(sorted(word[1::2]))
      return len(codes)
ob = Solution()




Updated on 04-Jul-2020 10:23:13