Sponsored
Sponsored
The two pointers approach uses two indices to represent the start and end of the string. The idea is to check for matching characters from both ends and shrink the string until the characters differ. Loop through the string, adjusting these pointers to remove any prefixes and suffixes with matching characters. This method is efficient as it only requires a single pass through the string.
Time Complexity: O(n), where n is the length of the string, because each character is visited at most twice.
Space Complexity: O(1), as no additional space is used apart from variables.
1def minimumLength(s):
2 left, right = 0, len(s) - 1
3 while left < right and s[left] == s[right]:
4 current_char = s[left]
5 while left <= right and s[left] == current_char:
6 left += 1
7 while left <= right and s[right] == current_char:
8 right -= 1
9 return right - left + 1
10
11s = "aabccabba"
12print(minimumLength(s)) # Output: 3
In this Python function, two pointers iterate from the start and end of the string. As long as the characters at the positions are equal, these characters are skipped to shrink the string effectively, resulting in the minimal remaining string's length.
This recursive approach tries to minimize the string length by removing valid prefixes and suffixes. The base case is when no more valid removals are possible, and the remaining string length is minimal. Each recursive call attempts to strip away the symmetric ends and proceeds with the interior until the results match.
Time Complexity: O(n), since it navigates through the string at minimal overhead.
Space Complexity: O(n) due to recursion depth management.
This C program uses a recursive function recursiveLength
to mimic the elimination process. It checks character consistency at the string bounds and develops further recursive calls, adjusting boundaries until no more symmetrical character matches exist.