101 Logo
onenoughtone

Code Implementation

String End Trimmer Implementation

Below is the implementation of the string end trimmer:

solution.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
/**
* Two Pointers Approach
* Time Complexity: O(n) - We might need to traverse the entire string once
* Space Complexity: O(1) - We only use a constant amount of extra space
*
* @param {string} s - The input string
* @return {number} - The minimum length after performing the operations
*/
function minimumLength(s) {
let left = 0;
let right = s.length - 1;
// Continue until pointers meet or characters at both ends are different
while (left < right && s[left] === s[right]) {
const current = s[left];
// Skip all consecutive occurrences of current from the left
while (left <= right && s[left] === current) {
left++;
}
// Skip all consecutive occurrences of current from the right
while (left <= right && s[right] === current) {
right--;
}
}
// Return the length of the remaining string
return right - left + 1;
}

Step-by-Step Explanation

Let's break down the implementation:

  1. 1. Understand the Problem: First, understand that we need to repeatedly remove equal characters from both ends of the string until we can't do so anymore, and return the minimum possible length of the resulting string.
  2. 2. Set Up Two Pointers: Initialize two pointers: left at the beginning of the string and right at the end.
  3. 3. Implement the Two-Pointer Approach: Use a while loop to continue until the pointers meet or the characters at both ends are different.
  4. 4. Handle Character Removal: When characters at both ends are the same, remove all consecutive occurrences of that character from both ends.
  5. 5. Calculate the Result: Return the length of the remaining string, which is right - left + 1.
  6. 6. Handle Edge Cases: Consider edge cases such as when the entire string consists of the same character or when the string has a length of 0 or 1.
  7. 7. Test the Solution: Verify the solution with the provided examples and additional test cases.
ProblemSolutionCode
101 Logo
onenoughtone