Camel
Peter
Peter Campbell Smith

Powering to the origin

Weekly challenge 349 — 24 November 2025

Week 349: 24 Nov 2025

Task 1

Task — Power string

You are given a string. Write a script to return the power of the given string. The power of the string is the maximum length of a non-empty substring that contains only one unique character.

Examples


Example 1
Input: $str = 'textbook'
Output: 2
Breakdown: 't', 'e', 'x', 'b', 'oo', 'k'
The longest substring with one unique character is 'oo'.

Example 2
Input: $str = 'aaaaa'
Output: 5

Example 3
Input: $str = 'hoorayyy'
Output: 3
Breakdown: 'h', 'oo', 'r', 'a', 'yyy'
The longest substring with one unique character is 'yyy'.

Example 4
Input: $str = 'x'
Output: 1

Example 5
Input: $str = 'aabcccddeeffffghijjk'
Output: 4
Breakdown: 'aa', 'b', 'ccc', 'dd', 'ee', 'ffff', 'g', 'h',
   'i', 'jj', 'k'
The longest substring with one unique character is 'ffff'.

Analysis

This is another challenge that allows for a wide range of different solutions.

Mine is to start by looking for $chars = length($string) consecutive identical characters using m|(.)\1{$chars}| and then decrementing $chars by 1 until I find a match.

It would be more efficient to step along the string incrementing $max if this character matches the previous one or setting $max to 1 if not, but it's hard to think of a use case where efficiency would matter.

Try it 

Try running the script with any input:



example: spoon moon moooo glue

Script


#!/usr/bin/perl

# Blog: http://ccgi.campbellsmiths.force9.co.uk/challenge

use v5.26;    # The Weekly Challenge - 2025-11-24
use utf8;     # Week 349 - task 1 - Power string
use warnings; # Peter Campbell Smith
binmode STDOUT, ':utf8';
use Encode;

power_string('textbook');
power_string('zzzzz');
power_string('abcde');
power_string('xoooxooooxoooooxoooo');

sub power_string {
    
    my ($string, $chars);
    
    # initialise
    $string = shift;    
    $chars = length($string);
    
    # decrement chars while consecutive characters
    while ($chars-- > 1) {
        last if $string =~ m|(.)\1{$chars}|;
    }
    
    say qq[\nInput:  '$string'];
    say qq[Output: ] . ($chars + 1);
}

Output


Input:  'textbook'
Output: 2

Input:  'zzzzz'
Output: 5

Input:  'abcde'
Output: 1

Input:  'xoooxooooxoooooxoooo'
Output: 5

 

Any content of this website which has been created by Peter Campbell Smith is in the public domain