Program to find minimum length of string after deleting similar ends in Python

Suppose we have a string s with only three characters 'a', 'b', and 'c'. We shall apply the following algorithm on the string any number of times −

  • Select a non-empty prefix from the s where all the characters in the prefix are same.

  • Select a non-empty suffix from the s where all the characters in the suffix are same.

  • The prefix and the suffix are disjoint.

  • The characters from the prefix and suffix must be the same.

  • Remove both the prefix and the suffix from s.

Finally, we have to find the minimum length of s after performing the above operation any number of times (possibly zero times).

So, if the input is like s = "aabccabba", then the output will be 3 because we at first we can select prefix = "aa" and suffix = "a", so that the string after removal is "bccabb", then select prefix = "b" and suffix "bb", so string after removal is "cca", which is of length 3.

To solve this, we will follow these steps −

  • s := make a queue with s

  • while size of s > 1 and s[0] is last element of s, do

    • chk := s[0]

    • while s and s[0] are same, do

      • delete left element from s

    • while s is not empty and last element of s is same as chk, do

      • delete last element from s

  • return size of s


Let us see the following implementation to get better understanding −

from collections import deque
def solve(s):
   s = deque(s)
   while len(s) > 1 and s[0] == s[-1]:
      chk = s[0]
      while s and s[0] == chk:
      while s and s[-1] == chk:
   return len(s)

s = "aabccabba"





Updated on: 06-Oct-2021


Kickstart Your Career

Get certified by completing the course

Get Started