The Weekly Challenge 381

Same Row Column and Smaller Greater Element

Task 1: Same Row Column

You are given a n x n matrix containing integers from 1 to n. Write a script to find if every row and every column contains all the integers from 1 to n.

Example Output

Input: @matrix = ([1, 2, 3, 4], [2, 3, 4, 1], [3, 4, 1, 2], [4, 1, 2, 3]) Output: true

Logic

Ensure each row has exactly n elements, and the set of values in the row matches {1..n}. Similarly, extract each column and ensure the set of values in the column matches {1..n}.

Perl Solution

ch-1.pl

sub same_row_column ($matrix) { my $n = scalar @$matrix; # Check rows for my $row (@$matrix) { return 0 if scalar @$row != $n; my %seen; for my $val (@$row) { return 0 if $val < 1 || $val > $n || $seen{$val}++; } } # Check columns for my $col_idx (0 .. $n - 1) { my %seen; for my $row_idx (0 .. $n - 1) { my $val = $matrix->[$row_idx][$col_idx]; return 0 if $val < 1 || $val > $n || $seen{$val}++; } } return 1; }

Python Solution

ch-1.py

def same_row_column(matrix: list[list[int]]) -> bool: n = len(matrix) # Check rows for row in matrix: if len(row) != n: return False if set(row) != set(range(1, n + 1)): return False # Check columns for col_idx in range(n): col = [matrix[row_idx][col_idx] for row_idx in range(n)] if set(col) != set(range(1, n + 1)): return False return True

Task 2: Smaller Greater Element

You are given an array of integers. Write a script to find the number of elements that have both a strictly smaller and greater element in the given array.

Example Output

Input: @int = (1, 1, 4, 8, 12, 12) Output: 2 (The elements are 4 and 8)

Logic

Find the minimum and maximum values in the array. Any element that is strictly greater than the minimum and strictly smaller than the maximum will have both a strictly smaller and strictly greater element in the array. Count and return the number of such elements.

Perl Solution

ch-2.pl

sub smaller_greater_element ($arr) { return 0 if scalar @$arr < 3; my $min = min @$arr; my $max = max @$arr; my $count = 0; for my $val (@$arr) { $count++ if $val > $min && $val < $max; } return $count; }

Python Solution

ch-2.py

def smaller_greater_element(arr: list[int]) -> int: if len(arr) < 3: return 0 min_val = min(arr) max_val = max(arr) return sum(1 for val in arr if min_val < val < max_val)