The Weekly Challenge 399

Longest Repeating Character & Longest Absolute Path

Official Challenge • My Solutions on GitHub

Task 1: Longest Repeating Character

You are given a string str and an integer k > 0. Write a script to change any character of str up to k times and return the length of the longest reachable substring of a single letter.

Examples

Input: $str = "AAAAA", $k = 2 => Output: 5 Input: $str = "ABCDE", $k = 4 => Output: 5 Input: $str = "AAABBBBAA", $k = 1 => Output: 5 Input: $str = "ABACADA", $k = 2 => Output: 5 Input: $str = "BAAABAAAA", $k = 1 => Output: 8

Algorithm & Approach

We use a sliding window [left..right] while tracking character frequencies inside the window and the highest frequency max_freq seen:

Runs in O(n) time and O(Σ) space.

Perl Solution

#!/usr/bin/env perl
use v5.38;
use warnings;
use Type::Params -sigs;
use Types::Standard qw(Int Str);
use Test::More;

signature_for longest_repeating_character => (
    method     => 0,
    positional => [ Str, Int ],
);

sub longest_repeating_character ( $str, $k ) {
    my @chars    = split //msx, $str;
    my %counts;
    my $left     = 0;
    my $max_freq = 0;
    my $best     = 0;

    for my $right ( 0 .. $#chars ) {
        my $ch = $chars[$right];
        $counts{$ch}++;
        $max_freq = $counts{$ch} if $counts{$ch} > $max_freq;

        while ( ( $right - $left + 1 ) - $max_freq > $k ) {
            $counts{ $chars[$left] }--;
            $left++;
        }

        my $win_len = $right - $left + 1;
        $best = $win_len if $win_len > $best;
    }

    return $best;
}

Python Solution

#!/usr/bin/env python3
"""Longest Repeating Character - Perl Weekly Challenge 399, Task 1."""

from __future__ import annotations

from collections import defaultdict
import unittest


def longest_repeating_character(text: str, k: int) -> int:
    """Return the longest single-letter substring length with at most k edits."""
    counts: dict[str, int] = defaultdict(int)
    left = 0
    max_freq = 0
    best = 0

    for right, ch in enumerate(text):
        counts[ch] += 1
        max_freq = max(max_freq, counts[ch])

        while (right - left + 1) - max_freq > k:
            counts[text[left]] -= 1
            left += 1

        best = max(best, right - left + 1)

    return best

Task 2: Longest Absolute Path

You are given a filesystem as a string. Write a script to return the length of the longest absolute path to a file in the abstracted file system, or 0 if there is no file.

Examples

Input: "dir\n\tsubdir1\n\t\tsubsubdir1\n\tsubdir2" => Output: 0 Input: "file1.txt\nfile2.ext\na.png" => Output: 9 Input: "my documents\n\tproject v1.0\n\t\tnotes v1.txt\n\timage.png" => Output: 38 Input: "root\n\ta\n\t\tb\n\t\t\tc.txt\n\td\n\t\te.txt" => Output: 14 Input: "a\n\tb\n\t\tc\n\t\t\td\n\t\t\t\te.txt\n\tvery_long_directory_name\n\t\tf.txt" => Output: 32

Algorithm & Approach

Each line's depth equals its leading tab count. We maintain an array/map depth_len storing the cumulative path length at each depth:

Runs in O(n) time where n is the input length.

Perl Solution

#!/usr/bin/env perl
use v5.38;
use warnings;
use Type::Params -sigs;
use Types::Standard qw(Str);
use Test::More;

signature_for longest_absolute_path => (
    method     => 0,
    positional => [Str],
);

sub longest_absolute_path ($fs) {
    my @depth_len;
    my $max_len = 0;

    for my $line ( split /\n/msx, $fs ) {
        my ($tabs) = $line =~ m/\A(\t*)/msx;
        my $depth  = length $tabs;
        my $name   = substr $line, $depth;

        my $cur_len = ( $depth == 0 ? 0 : $depth_len[ $depth - 1 ] + 1 ) + length $name;
        $depth_len[$depth] = $cur_len;

        if ( index( $name, q{.} ) != -1 ) {
            $max_len = $cur_len if $cur_len > $max_len;
        }
    }

    return $max_len;
}

Python Solution

#!/usr/bin/env python3
"""Longest Absolute Path - Perl Weekly Challenge 399, Task 2."""

from __future__ import annotations

import unittest


def longest_absolute_path(fs: str) -> int:
    """Return the length of the longest absolute file path, or 0 if none."""
    depth_len: dict[int, int] = {}
    max_len = 0

    for line in fs.split("\n"):
        name = line.lstrip("\t")
        depth = len(line) - len(name)
        cur_len = (0 if depth == 0 else depth_len[depth - 1] + 1) + len(name)
        depth_len[depth] = cur_len

        if "." in name:
            max_len = max(max_len, cur_len)

    return max_len