The Weekly Challenge 321

Unique Averages & Backspace Processing!

Original Challenge Link

Task 1: Distinct Average

"Balanced Removal: Counting Unique Mean Values!"

Given an even-length array, repeatedly remove the minimum and maximum values, calculate their average, and count how many unique averages were found.

The Strategy: First, sort the array in ascending order. Use two pointers: one at the start (min) and one at the end (max). In each step, calculate the average of the elements at these pointers, move the pointers toward each other, and store the average in a set (or hash) to automatically handle uniqueness.
Perl Implementation
sub distinct_average_count ($nums) {
    my @sorted = sort { $a <=> $b } @$nums;
    my %seen;
    for ( my ( $l, $r ) = ( 0, $#sorted ); $l < $r; ++$l, --$r ) {
        my $sum = $sorted[$l] + $sorted[$r];
        $seen{ sprintf( '%.12g', $sum ) } = 1;
    }
    return scalar keys %seen;
}
Python Implementation
def distinct_average_count(nums: Sequence[Fraction]) -> int:
    sorted_nums = sorted(nums)
    seen: set[Fraction] = set()
    left, right = 0, len(sorted_nums) - 1
    while left < right:
        seen.add((sorted_nums[left] + sorted_nums[right]) / 2)
        left += 1
        right -= 1
    return len(seen)

Task 2: Backspace Compare

"The Editor's Stack: Processing Backspace Characters!"

Determine if two strings are identical after processing the '#' character as a backspace (deleting the previous character).

The Strategy: A stack-based approach is perfect for backspace processing. Iterate through each character of the string: if it's a '#', pop from the stack (if not empty); otherwise, push the character onto the stack. After processing both strings, compare the resulting stacks for equality.
Perl Implementation
sub _apply_backspaces ($str) {
    my @stack;
    for my $ch ( split //, $str ) {
        if ( $ch eq '#' ) {
            pop @stack if @stack;
        } else {
            push @stack, $ch;
        }
    }
    return join '', @stack;
}

sub backspace_compare ($str1, $str2) {
    return _apply_backspaces($str1) eq _apply_backspaces($str2) ? 1 : 0;
}
Python Implementation
def _apply_backspaces(text: str) -> str:
    stack: list[str] = []
    for char in text:
        if char == "#":
            if stack:
                stack.pop()
        else:
            stack.append(char)
    return "".join(stack)

def backspace_compare(first: str, second: str) -> bool:
    return _apply_backspaces(first) == _apply_backspaces(second)