Program to partition two strings such that each partition forms anagram in Python

Suppose we have two non-empty strings s and t that are of the same length. We have to partition them into substrings such that each pair of s and t substring is the same size and they are the anagrams of each other. Now find the cut indexes such that it results in the maximum number of cuts of s and t. If no result is found, then return empty list.

So, if the input is like s = "bowcattiger" t = "owbactietgr", then the output will be [0, 3, 5, 6, 10], as we can partition the string into 5 partitions such that each string is an anagram of each other. s = ["bow", "ca", "t", "tige", "r"], t = ["owb", "ac", "t", "ietg", "r"]

To solve this, we will follow these steps −

  • intervals := a new list
  • cs := a map with character present in s and its frequency
  • ct := a map with character present in t and its frequency
  • if cs is not same as ct, then
    • return a new list
  • for x in range size of s - 1 down to 0, do
    • cs[s[x]] := cs[s[x]] - 1
    • ct[t[x]] := ct[t[x]] - 1
    • if cs is same as ct, then
      • insert x at the end of intervals
  • sort the list intervals and return

Let us see the following implementation to get better understanding −


 Live Demo

from collections import Counter
class Solution:
   def solve(self, a, b):
      intervals = []
      ca = Counter(a)
      cb = Counter(b)
      if ca != cb:
         return []
      for x in reversed(range(len(a))):
            ca[a[x]] -= 1
            cb[b[x]] -= 1
            if ca == cb:
      return sorted(intervals)
ob = Solution()
s = "bowcattiger"
t = "owbactietgr"
print(ob.solve(s, t))


"bowcattiger", "owbactietgr"


[0, 3, 5, 6, 10]