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

PythonServer Side ProgrammingProgramming

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 −


 Live Demo

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


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


Published on 05-Oct-2020 06:24:34