#1750
Minimum Length of String After Deleting Similar Ends
MediumTwo PointersStringTwo PointersString Manipulation
Approaches
Brute ForceOptimal
Complexity Comparison
| Brute Force | Optimal Solution★ | |
|---|---|---|
| Time | O(n²) | O(n) |
| Space | O(1) | O(1) |
💡
Intuition
Time O(n)Space O(1)
The optimal solution uses a two-pointer technique to efficiently find and remove matching characters from both ends of the string. This approach minimizes unnecessary iterations and directly targets the characters to be removed.
⚙️
Algorithm
5 steps- 1Step 1: Initialize two pointers, one at the start (left) and one at the end (right) of the string.
- 2Step 2: Move the left pointer to the right as long as it points to the same character as the first character.
- 3Step 3: Move the right pointer to the left as long as it points to the same character as the last character.
- 4Step 4: If the characters at the left and right pointers are the same, remove them and repeat the process.
- 5Step 5: Return the length of the remaining string.
solution.py8 lines
1def minimumLength(s):
2 left, right = 0, len(s) - 1
3 while left < right and s[left] == s[right]:
4 while left < right and s[left] == s[0]:
5 left += 1
6 while left < right and s[right] == s[-1]:
7 right -= 1
8 return right - left + 1ℹ
Complexity note: The time complexity is O(n) because we only traverse the string once with the two pointers, making it linear in relation to the length of the string.
- 1Matching characters at both ends can be removed simultaneously.
- 2The two-pointer technique is efficient for problems involving string manipulation.
Solutions and explanations are original Tejav content. Problem titles © LeetCode — use the LeetCode button above for the full problem statement.