| 04 October 2026 | Challenge 392 |
Palindromic Products
Task 1: Convert Palindrome
Submitted by: Mohammad Sajid Anwar
You are given a string.
Write a script to convert the given string to palindrome by adding characters in front of it.
Example 1
Input: $str = "pinnipeds"
Output: "sdepinnipeds"
Example 2
Input: $str = "abcd"
Output: "dcbabcd"
Example 3
Input: $str = "bananas"
Output: "sananabananas"
Example 4
Input: $str = "dissident"
Output: "tnedissident"
Example 5
Input: $str = "cailliachs"
Output: "shcailliachs"
Solution
With decreasing length, we may check if the string’s prefix is a palindrome. This check must succeed at some point, at least at the length of one.
Then prepend the non-palindromic tail in reversed order to the string.
Perl
use strict;
use warnings;
use experimental 'signatures';
sub convert_palindrome ($str) {
for my $l (reverse 1 .. length($str)) {
return reverse(substr($str, $l)) . $str
if substr($str, 0, $l) eq reverse substr($str, 0, $l);
}
}
See the full solution to task 1.
J
convert_palindrome =: (] ,~ [: |. ] }.~ >:@i:&1@((|. -: ])\)) : [:
convert_palindrome 'pinnipeds'
sdepinnipeds
See the full solution.
Task 2: Words Length Product
Submitted by: Mohammad Sajid Anwar
You are given an array of strings.
Write a script to return the maximum value of len($words[i]) * len($words[j]) where the two words do not share common letters. If no such two words exist, return 0.
Example 1
Input: @words = ("a", "ab", "abc", "d", "de", "def")
Output: 9
Two words are "abc" and "def".
Example 2
Input: @words = ("a", "aa", "aaa", "aaaa")
Output: 0
Since no two words can be chosen without sharing letters, the result is 0.
Example 3
Input: @words = ("meet", "app", "code", "sky", "bold")
Output: 16
Two words are "meet" and "bold".
Example 4
Input: @words = ("a", "ab", "abc", "abcd", "efghi")
Output: 20
Two words are "abcd" and "efghi".
Example 5
Input: @words = ("xyz", "w", "abcdefg", "hij")
Output: 21
Two words are "abcdefg" and "hij".
Solution
Perl
Convert one word to a regex that represents a character class of all of its letters. Then match all following words against the regex. If the match fails, find the maximum word length product.
use strict;
use warnings;
sub word_length_product {
my $wlp = 0;
while (my $w1 = shift) {
my $r = qr([\Q$w1\E]);
for my $w2 (@_) {
if ($w2 !~ $r) {
my $p = length($w1) * length($w2);
$wlp = $p if $p > $wlp;
}
}
}
$wlp;
}
See the full solution to task 2.
J
Compare words pairwise for common characters and multiply the negated result with the product of the strings’ lengths.
word_length_product =: ([: >./@, */~@(# S:0) * -.@(+./)@:e.&>/~) : [:
word_length_product ;:'meet app code sky bold'
16
See the full solution.