The Weekly Challenge 341

Typing with Broken Keys & Prefix Reversal!

Original Challenge Link

Task 1: Broken Keyboard

"Can You Type It? Count the Surviving Words!"

Given a string and a list of broken keys, count how many words can be typed completely without using any of the broken keys.

The Strategy: Store broken keys in a hash set for O(1) lookup. Split the string into words and for each word check every character (case-insensitive) against the broken set. Count words where no character matches a broken key.
Perl Implementation
sub broken_keyboard {
    my ( $str, @broken_keys ) = @_;
    my %broken = map { $_ => 1 } @broken_keys;

    my @words = split /\s+/, $str;
    my $count = 0;

    foreach my $word (@words) {
        my $can_type = 1;
        foreach my $char ( split //, lc($word) ) {
            if ( exists $broken{$char} ) {
                $can_type = 0;
                last;
            }
        }
        $count++ if $can_type;
    }

    return $count;
}
Python Implementation
def broken_keyboard(text: str, *broken_keys: str) -> int:
    """Count words that can be typed without using any broken key."""
    broken = set(broken_keys)

    def can_type(word: str) -> bool:
        return all(ch.lower() not in broken for ch in word)

    return sum(1 for word in text.split() if can_type(word))

Task 2: Reverse Prefix

"Flip the Front: Reverse Up to the Target Character!"

Given a string and a character, reverse the prefix of the string up to and including the first occurrence of that character. If the character is not found, return the original string unchanged.

The Strategy: Find the index of the first occurrence of the target character. If found, extract the prefix (up to and including the character), reverse it, and concatenate with the remainder. If not found, return the string as-is.
Perl Implementation
sub reverse_prefix {
    my ( $str, $char ) = @_;
    my $pos = index( $str, $char );

    return $str if $pos == -1;

    my $prefix = substr( $str, 0, $pos + 1 );
    return reverse($prefix) . substr( $str, $pos + 1 );
}
Python Implementation
def reverse_prefix(text: str, char: str) -> str:
    """Reverse the prefix up to and including the first occurrence of char."""
    pos = text.find(char)
    if pos == -1:
        return text

    prefix = text[:pos + 1]
    return prefix[::-1] + text[pos + 1:]