Task 1: Duplicate Removals
"Pop the Pair: Remove Adjacent Duplicates Until It's Clean!"
Given a string, repeatedly remove adjacent duplicate pairs until the string stabilises. For example, "abbaca" becomes "ca" after removing "bb" then "aa".
The Strategy: Use a stack. Walk left to right: if the current character matches the stack top, pop (removing the pair). Otherwise push. After the scan, the stack contains the fully reduced string. This is a classic single-pass O(n) algorithm.
Perl Implementation
sub duplicate_removals ($str) {
_assert_plain_string($str);
my @stack;
for my $char ( split //, $str ) {
if ( @stack && $stack[-1] eq $char ) {
pop @stack;
}
else {
push @stack, $char;
}
}
return join q(), @stack;
}
Python Implementation
def duplicate_removals(text: str) -> str:
"""Remove adjacent duplicate pairs repeatedly until stable."""
stack: list[str] = []
for ch in text:
if stack and stack[-1] == ch:
stack.pop()
else:
stack.append(ch)
return "".join(stack)