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.
1#include <iostream>
2#include <string>
3
4int minimumLength(std::string s) {
5 int n = s.size();
6 int left = 0, right = n - 1;
7 while (left < right && s[left] == s[right]) {
8 char currentChar = s[left];
9 while (left <= right && s[left] == currentChar) {
10 left++;
11 }
12 while (left <= right && s[right] == currentChar) {
13 right--;
14 }
15 }
16 return right - left + 1;
17}
18
19int main() {
20 std::string s = "aabccabba";
21 std::cout << minimumLength(s) << std::endl; // Output: 3
22 return 0;
23}
This C++ solution is similar to the C solution, leveraging a two-pointer technique to traverse the string and adjust the pointers inward when matching characters are encountered. Through this process, the function determines the minimum length of the string after valid deletions.
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.
JavaScript's recursion dives into string symmetry by comparing opposite values. As character pairs are exhaustively eliminated through repeated invocations, lengths are minimized, underscoring alternatives zero-length paths.