The Weekly Challenge 375

Single Common Word and Find K-Beauty

Task 1: Single Common Word

You are given two arrays of strings.

Write a script to return the number of strings that appear exactly once in each of the two given arrays (case-sensitive comparison).

Example 1

Input: @array1 = ("apple", "banana", "cherry") @array2 = ("banana", "cherry", "date") Output: 2

Example 2

Input: @array1 = ("a", "ab", "abc") @array2 = ("a", "a", "ab", "abc") Output: 2

Example 3

Input: @array1 = ("Hello", "world") @array2 = ("hello", "world") Output: 1

Logic

Compute frequency hashes for both arrays. Iterating through strings of the first hash, select those with exactly count 1 which also appear exactly count 1 in the second hash. This guarantees a linear time solution of $O(N + M)$ without nested loops.

Perl Solution

ch-1.pl

sub single_common_word ($arr1_ref, $arr2_ref) { die "First argument must be an array reference" unless ref($arr1_ref) eq 'ARRAY'; die "Second argument must be an array reference" unless ref($arr2_ref) eq 'ARRAY'; my %count1; my %count2; $count1{$_}++ for @$arr1_ref; $count2{$_}++ for @$arr2_ref; my $count = 0; for my $word (keys %count1) { if ($count1{$word} == 1 && ($count2{$word} // 0) == 1) { $count++; } } return $count; }

Python Solution

ch-1.py

from collections import Counter def single_common_word(arr1: list[str], arr2: list[str]) -> int: count1 = Counter(arr1) count2 = Counter(arr2) return sum( 1 for word, freq in count1.items() if freq == 1 and count2.get(word, 0) == 1 )

Task 2: Find K-Beauty

You are given a number and a digit k.

Write a script to find the K-Beauty of the given number. The K-Beauty of an integer number is defined as the number of substrings of the given number (when read as a string) that have a length of k and are a divisor of the given number.

Example 1

Input: num = 240, k = 2 Output: 2

Example 2

Input: num = 430043, k = 2 Output: 2

Logic

Extract all substrings of length k. Convert each to a numerical integer. Verify it is non-zero (to prevent division by zero) and check if the original number is evenly divisible by it. Count all matching divisors.

Perl Solution

ch-2.pl

sub k_beauty ($num, $k) { die "First argument must be an integer" unless $num =~ /^\d+$/; die "Second argument must be an integer" unless $k =~ /^\d+$/; my $str = "$num"; my $len = length($str); my $count = 0; for my $i (0 .. $len - $k) { my $sub = substr($str, $i, $k); my $val = int($sub); if ($val != 0 && $num % $val == 0) { $count++; } } return $count; }

Python Solution

ch-2.py

def k_beauty(num: int, k: int) -> int: num_str = str(num) count = 0 for i in range(len(num_str) - k + 1): substring = num_str[i : i + k] val = int(substring) if val != 0 and num % val == 0: count += 1 return count