Task 1: Reverse Substring
You are given a string. Write a script to find whether any substring of length 2 is also present in the reverse of the given string.
Example Output
Input: $str = "abcba"
Output: true
Input: $str = "abcd"
Output: false
Logic
Reverse the given string. Then iterate through all consecutive pairs of characters (length 2 substrings) from index 0 to length - 2. If any pair is found as a substring within the reversed string, return true; otherwise, return false.
Perl Solution
ch-1.pl
sub has_reverse_substring ($str) {
my $len = length($str);
return 0 if $len < 2;
my $rev = reverse($str);
for my $i ( 0 .. $len - 2 ) {
my $sub = substr( $str, $i, 2 );
return 1 if index( $rev, $sub ) != -1;
}
return 0;
}
Python Solution
ch-1.py
def has_reverse_substring(s: str) -> bool:
"""Return True if any length 2 substring of s is present in reverse(s)."""
if len(s) < 2:
return False
rev = s[::-1]
for i in range(len(s) - 1):
sub = s[i : i + 2]
if sub in rev:
return True
return False
Task 2: Prefix and Suffix
You are given an array of strings. Write a script to find the count of pairs (str1, str2) at distinct indices i < j such that str1 is both a prefix and a suffix of str2.
Example Output
Input: @array = ("a", "aba", "ababa", "aa")
Output: 4
Input: @array = ("pa", "papa", "ma", "mama")
Output: 2
Logic
Iterate over all pairs of indices (i, j) with 0 <= i < j < n. For each pair, check if array[j] begins with and ends with array[i]. Increment the counter for every match found.
Perl Solution
ch-2.pl
sub count_prefix_suffix_pairs (@array) {
my $count = 0;
my $n = scalar @array;
for my $i ( 0 .. $n - 2 ) {
my $s1 = $array[$i];
my $len = length($s1);
for my $j ( $i + 1 .. $n - 1 ) {
my $s2 = $array[$j];
next if length($s2) < $len;
if ( substr( $s2, 0, $len ) eq $s1 && substr( $s2, -$len ) eq $s1 ) {
$count++;
}
}
}
return $count;
}
Python Solution
ch-2.py
def count_prefix_suffix_pairs(array: list[str]) -> int:
"""Return the total count of pairs (i, j) where array[i] is prefix and suffix of array[j]."""
count = 0
n = len(array)
for i in range(n - 1):
s1 = array[i]
for j in range(i + 1, n):
s2 = array[j]
if s2.startswith(s1) and s2.endswith(s1):
count += 1
return count