The Weekly Challenge 329

Integer Extraction & Nice Substrings!

Original Challenge Link

Task 1: Counter Integers

"The Integer Filter: Finding Distinct Numbers!"

Extract all unique integers from a string containing lowercase letters and digits by replacing non-digit characters with spaces.

The Strategy: Both solutions follow the same logic: replace all non-digit characters (regex \D or [^0-9]) with spaces. Split the resulting string by whitespace to get individual number chunks. Maintain a "seen" set/hash to filter out duplicates while preserving the original order of first appearance.
Perl Implementation
sub counter_integers {
    my ($str) = @_;
    my $digits_as_spaces = $str =~ s/\D+/ /gr;
    my %seen;
    my @uniq;
    for my $chunk (split /\s+/, $digits_as_spaces) {
        next unless length $chunk;
        next if $seen{$chunk}++;
        push @uniq, 0 + $chunk;
    }
    return \@uniq;
}
Python Implementation
def counter_integers(text: str) -> list[int]:
    digits_as_spaces = "".join(ch if ch.isdigit() else " " for ch in text)
    seen = set()
    result = []
    for chunk in digits_as_spaces.split():
        if chunk not in seen:
            seen.add(chunk)
            result.append(int(chunk))
    return result

Task 2: Nice String

"Perfect Pairs: Finding the Longest Nice Substring!"

A string is "nice" if every letter it contains appears in both its uppercase and lowercase forms. Find the longest such substring.

The Strategy: A simple brute-force approach works well for strings of reasonable length. We iterate through all possible substrings (start and end indices). For each candidate, we check if it is "nice" by verifying that for every unique character in the substring, its lowercase and uppercase counterparts are also present. We keep track of the longest nice substring found.
Perl Implementation
sub is_nice {
    my ($s) = @_;
    my %letters;
    $letters{$_}++ for split //, $s;
    for my $ch (keys %letters) {
        return 0 unless exists $letters{lc $ch} && exists $letters{uc $ch};
    }
    return 1;
}

sub longest_nice_substring {
    my ($s) = @_;
    my $best = '';
    for my $start (0 .. length($s) - 1) {
        for my $end ($start + 1 .. length($s)) {
            my $candidate = substr $s, $start, $end - $start;
            next if length($candidate) <= length($best);
            $best = $candidate if is_nice($candidate);
        }
    }
    return $best;
}
Python Implementation
def is_nice(s: str) -> bool:
    chars = set(s)
    return all(c.lower() in chars and c.upper() in chars for c in chars)

def longest_nice_substring(s: str) -> str:
    best = ""
    n = len(s)
    for i in range(n):
        for j in range(i + 1, n + 1):
            candidate = s[i:j]
            if len(candidate) > len(best) and is_nice(candidate):
                best = candidate
    return best