The Weekly Challenge 372

Space Mechanics & Substring Symmetry!

Original Challenge Link

Task 1: Rearrange Spaces

"Text Tuning: Harmonizing White Space Between Words!"

Rearrange spaces in a string to distribute them equally between words, with any remainder placed at the end.

The Strategy: First, count the total number of spaces and extract all non-empty words. If there's only one word, all spaces go after it. Otherwise, calculate the number of gaps (word count - 1). Divide total spaces by gaps to get spaces per gap, and use the modulo operator for the remainder. Join the words using the calculated gap size and append the remainder.
Perl Implementation
sub rearrange_spaces ($str) {
    my $num_spaces = ( $str =~ tr/ // );
    my @words      = grep { length($_) } split /\s+/, $str;
    my $num_words  = scalar @words;

    if ( $num_words == 1 ) {
        return $words[0] . ( ' ' x $num_spaces );
    }

    my $num_gaps       = $num_words - 1;
    my $spaces_per_gap = int( $num_spaces / $num_gaps );
    my $remainder      = $num_spaces % $num_gaps;

    return join( ( ' ' x $spaces_per_gap ), @words ) . ( ' ' x $remainder );
}
Python Implementation
def rearrange_spaces(text: str) -> str:
    num_spaces = text.count(" ")
    words = text.split()
    num_words = len(words)

    if num_words == 1:
        return words[0] + (" " * num_spaces)

    num_gaps = num_words - 1
    spaces_per_gap = num_spaces // num_gaps
    remainder = num_spaces % num_gaps

    return (" " * spaces_per_gap).join(words) + (" " * remainder)

Task 2: Largest Substring

"Character Chasm: Spanning the Distance Between Identical Twins!"

Find the length of the longest substring between any two identical characters in a string, excluding the characters themselves.

The Strategy: Use a dictionary (hash) to record the first occurrence of each character. Iterate through the string; if a character has been seen before, calculate the distance between the current index and the recorded first index minus one. Keep track of the maximum such distance. If no duplicates are found, return -1.
Perl Implementation
sub largest_substring ($str) {
    my %first_pos;
    my $max_len = -1;
    my @chars = split //, $str;
    for ( my $i = 0; $i < @chars; $i++ ) {
        my $char = $chars[$i];
        if ( exists $first_pos{$char} ) {
            my $len = $i - $first_pos{$char} - 1;
            $max_len = $len if $len > $max_len;
        } else {
            $first_pos{$char} = $i;
        }
    }
    return $max_len;
}
Python Implementation
def largest_substring(text: str) -> int:
    first_pos: dict[str, int] = {}
    max_len = -1
    for i, char in enumerate(text):
        if char in first_pos:
            length = i - first_pos[char] - 1
            if length > max_len:
                max_len = length
        else:
            first_pos[char] = i
    return max_len