Program to find how many distinct rotation groups are there for a list of words in Python


Suppose we have rotation group for a string that holds all of its unique rotations. If the input is like, "567" then this can be rotated to "675" and "756" and they are all in the same rotation group. Now if we have a list of strings words, we have to group each word by their rotation group, and find the total number of groups.

So, if the input is like words = ["xyz", "ab", "ba", "c", "yzx"], then the output will be 3, as There are three rotation groups − ["xyz", "yzx"], ["ab", "ba"], ["c"].

To solve this, we will follow these steps −

  • s:= a new set
  • ct:= 0
  • for each i in words, do
    • if i not in s, then
      • ct := ct + 1
    • for j in range 0 to size of i, do
      • temp := substring of i[from index j to end] concatenate substring of i [from beginning to j])
      • insert temp to s
  • return ct

Let us see the following implementation to get better understanding −

Example

 Live Demo

class Solution:
   def solve(self, words):
      s=set()
      ct=0
      for i in words:
         if i not in s:
            ct+=1
         for j in range(len(i)):
            s.add(i[j:]+i[:j])
      return ct
ob = Solution()
print(ob.solve(["xyz", "ab", "ba", "c", "yzx"]))

Input

["xyz", "ab", "ba", "c", "yzx"]

Output

3

Updated on: 05-Oct-2020

168 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements