Minimum Length of String After Deleting Similar Ends
Problem
Repeatedly remove a non-empty prefix and an equal-length non-empty suffix that share the same single character, requiring ls = "cabaabac"0
def minimum_length(s):
l, r = 0, len(s) - 1
while l < r and s[l] == s[r]:
c = s[l]
while l <= r and s[l] == c: l += 1
while l <= r and s[r] == c: r -= 1
return max(0, r - l + 1)
function minimumLength(s) {
let l = 0, r = s.length - 1;
while (l < r && s[l] === s[r]) {
const c = s[l];
while (l <= r && s[l] === c) l++;
while (l <= r && s[r] === c) r--;
}
return Math.max(0, r - l + 1);
}
class Solution {
public int minimumLength(String s) {
int l = 0, r = s.length() - 1;
while (l < r && s.charAt(l) == s.charAt(r)) {
char c = s.charAt(l);
while (l <= r && s.charAt(l) == c) l++;
while (l <= r && s.charAt(r) == c) r--;
}
return Math.max(0, r - l + 1);
}
}
int minimumLength(string s) {
int l = 0, r = (int)s.size() - 1;
while (l < r && s[l] == s[r]) {
char c = s[l];
while (l <= r && s[l] == c) l++;
while (l <= r && s[r] == c) r--;
}
return max(0, r - l + 1);
}
Explanation
Each move strips a prefix and a matching suffix made of the same single character. Since both ends must be that same character, we only ever act on the outermost characters, so two pointers l and r shrinking inward capture the whole process.
Look at the two ends. If s[l] != s[r], no more removals are possible and we stop. If they are equal, call that character c and peel away the entire run of c from each side: advance l while s[l] == c and pull r back while s[r] == c.
Peeling whole runs at once is important because the prefix and suffix you remove can be any length, so it is always best to take every leading and trailing c in one go. Then we repeat with the new ends.
When the loop ends, the leftover is the slice from l to r, whose length is r - l + 1 (clamped to 0 if the pointers crossed).
Example: s = "cabaabac". Strip the c's to get "abaaba", then the a's to get "baab", then the b's to get "aa", then the a's to get "". The minimum length is 0.