Program to find number of good ways to split a string using Python

Suppose we have a string s. Now a split is said to be a good split when we can split s into 2 non-empty strings p and q where its concatenation is equal to s and the number of distinct letters in p and q are the equal. We have to find the number of good splits we can make in s.

So, if the input is like s = "xxzxyx", then the output will be 2 as there are multiple ways of splitting but if we split like ("xxz", "xyx") or ("xxzx", "yx") then they are good.

To solve this, we will follow these steps −

  • result := 0

  • left := an empty mal to count frequency of items

  • right := Count each character's frequency present in s

  • for each c in s, do

    • left[c] := left[c] + 1

    • right[c] := right[c] - 1

    • if right[c] is zero, then

      • remove right[c]

    • if size of left is same as size of right, then

      • result := result + 1

  • return result

Let us see the following implementation to get better understanding −


 Live Demo

from collections import Counter
def solve(s):
   result = 0
   left, right = Counter(), Counter(s)
   for c in s:
      left[c] += 1
      right[c] -= 1
      if not right[c]:
         del right[c]
      if len(left) == len(right):
         result += 1
   return result
s = "xxzxyx"





Updated on: 29-May-2021


Kickstart Your Career

Get certified by completing the course

Get Started