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 can apply the following algorithm on the string any number of times to minimize its length:

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

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

  • The prefix and suffix must be disjoint (non-overlapping).

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

  • Remove both the prefix and the suffix from s.

Our goal is to find the minimum possible length of s after performing this operation any number of times.

Example Walkthrough

Consider the string s = "aabccabba":

  • First, select prefix = "aa" and suffix = "a" (same character 'a'), resulting in "bccabb"

  • Then, select prefix = "b" and suffix = "bb" (same character 'b'), resulting in "cca"

  • No more valid prefix-suffix pairs can be found, so the final length is 3

Algorithm

The approach uses a deque (double-ended queue) to efficiently remove characters from both ends:

  1. Convert the string into a deque for O(1) operations at both ends

  2. While the string has more than 1 character and the first and last characters are the same:

    • Store the matching character

    • Remove all consecutive characters of this type from the left

    • Remove all consecutive characters of this type from the right

  3. Return the final length of the deque

Implementation

from collections import deque

def solve(s):
    s = deque(s)
    
    while len(s) > 1 and s[0] == s[-1]:
        chk = s[0]
        
        # Remove all consecutive characters from left
        while s and s[0] == chk:
            s.popleft()
        
        # Remove all consecutive characters from right
        while s and s[-1] == chk:
            s.pop()
    
    return len(s)

# Test the function
s = "aabccabba"
result = solve(s)
print(f"Minimum length after operations: {result}")
Minimum length after operations: 3

How It Works

The algorithm simulates the optimal strategy by always removing the maximum possible characters in each iteration. Using a deque allows efficient removal from both ends without shifting array elements.

Step 1: "aabccabba" aa bccabb a ? Remove "aa" and "a" Step 2: "bccabb" b cca bb ? Remove "b" and "bb" Step 3: "cca" cca ? No matching ends, final length = 3 Legend: Prefix/Suffix (same char) Remaining string

Time and Space Complexity

  • Time Complexity: O(n) where n is the length of the string

  • Space Complexity: O(n) for the deque storage

Conclusion

This algorithm efficiently finds the minimum string length by repeatedly removing matching character sequences from both ends. The deque data structure enables optimal performance for this two-pointer approach.

Updated on: 2026-03-26T14:04:07+05:30

431 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements