The Weekly Challenge 317

Acronym Verification & String Swaps!

Original Challenge Link

Task 1: Acronyms

"Initial Integrity: Verifying Target Word Acronyms!"

Given an array of words and a target string, determine if the target word is the concatenation of the first letter of each word in the array.

The Strategy: Iterate through the list of words. For each word, extract its first character. Concatenate these extracted characters to form a candidate acronym string. Compare this candidate with the provided target string for an exact match.
Perl Implementation
sub is_acronym {
    my ( $words, $target ) = @_;
    return 0 if !$words || !@$words || !$target;
    my $acronym = join '', map { substr( $_, 0, 1 ) } @$words;
    return $acronym eq $target ? 1 : 0;
}
Python Implementation
def is_acronym(words: list[str], target: str) -> bool:
    if not words or not target:
        return False
    acronym = ''.join(word[0] for word in words if word)
    return acronym == target

Task 2: Friendly Strings

"Swap Synergy: Reaching Equality via a Single Move!"

Determine if two strings can be made identical by swapping exactly two letters in one of them.

The Strategy: First, check if the strings are identical (no swap needed) or have different lengths. If they are unequal but have the same length, iterate through both strings to find all indices where their characters differ. If there are exactly two such positions, verify if the characters at these positions in the first string match the characters in the reversed order at the same positions in the second string (a "cross-swap").
Perl Implementation
sub is_friendly_string {
    my ( $str1, $str2 ) = @_;
    return 0 if !$str1 || !$str2 || length($str1) != length($str2);
    return 1 if $str1 eq $str2;

    my @diff;
    for my $i ( 0 .. length($str1) - 1 ) {
        push @diff, [ substr( $str1, $i, 1 ), substr( $str2, $i, 1 ) ]
          if substr( $str1, $i, 1 ) ne substr( $str2, $i, 1 );
    }

    if ( @diff == 2 ) {
        return 1 if $diff[0][0] eq $diff[1][1] && $diff[0][1] eq $diff[1][0];
    }
    return 0;
}
Python Implementation
def is_friendly_string(str1: str, str2: str) -> bool:
    if not str1 or not str2 or len(str1) != len(str2):
        return False
    if str1 == str2:
        return True

    diffs = [(str1[i], str2[i]) for i in range(len(str1)) if str1[i] != str2[i]]

    if len(diffs) == 2:
        (c1, c2), (c3, c4) = diffs
        return c1 == c4 and c2 == c3

    return False