The Weekly Challenge 340

Stack Smashing Duplicates & Number Sequences!

Original Challenge Link

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)

Task 2: Ascending Numbers

"Spot the Trend: Are the Numbers Increasing?"

Given a space-separated string containing words and numbers, determine whether the numbers extracted in order form a strictly increasing sequence.

The Strategy: Split on spaces, filter tokens that are valid non-negative integers (no leading zeros except "0"), then compare each to the previous. Return false if any number is less than or equal to the last seen value. Otherwise return true.
Perl Implementation
sub ascending_numbers ($str) {
    _assert_plain_string($str);

    my $last;
    for my $token ( split / /, $str ) {
        next unless _is_valid_integer_token($token);

        my $value = 0 + $token;
        return 0 if defined $last && $value <= $last;
        $last = $value;
    }

    return 1;
}

sub _is_valid_integer_token ($token) {
    return $token eq '0' || $token =~ /\A[1-9]\d*\z/;
}
Python Implementation
def ascending_numbers(text: str) -> bool:
    """Check if numbers in the text form a strictly increasing sequence."""
    def is_valid_int(token: str) -> bool:
        return token == "0" or (token.isdigit() and token[0] != "0")

    last: int | None = None
    for token in text.split():
        if not is_valid_int(token):
            continue
        value = int(token)
        if last is not None and value <= last:
            return False
        last = value
    return True