You are given an array of strings and a character separator. Write a script to return all words separated by the given character excluding empty string.
Iterate over each string in @words and split it on the literal separator (using \Q...\E in Perl so regex metacharacters like . and $ are escaped automatically, and str.split(separator) in Python). Filter out any empty strings produced by leading, trailing, or consecutive separators, and collect the remaining substrings in order. This runs in O(n) time and O(n) space, where n is the total number of characters across all input words.
ch-1.pl)#!/usr/bin/env perl
use v5.38;
use warnings;
use Type::Params -sigs;
use Types::Standard qw(ArrayRef Str);
use Test::More;
signature_for split_strings => (
method => 0,
positional => [ ArrayRef[Str], Str ],
);
sub split_strings ( $words, $separator ) {
my @result = grep { $_ ne '' } map { split /\Q$separator\E/, $_ } @$words;
return \@result;
}
ch-1.py)def split_strings(words: list[str], separator: str) -> list[str]:
"""Split each string in words by separator and return non-empty parts."""
result: list[str] = []
for word in words:
result.extend(part for part in word.split(separator) if part)
return result
You are given an m x n binary matrix i.e. only 0 and 1 where 1 always appear before 0. A row i is weaker than a row j if the number of 1s in row i is less than in row j, or both rows have the same number of 1s and i < j. Write a script to return the order of rows from weakest to strongest.
Pair each row with its 1-count and its original row index: (ones_count, index). Sort these pairs primarily by ones_count ascending and secondarily by index ascending. Finally, extract the row indices from the sorted pairs. This runs in O(m · n + m log m) time and O(m) extra space.
ch-2.pl)#!/usr/bin/env perl
use v5.38;
use warnings;
use Type::Params -sigs;
use Types::Standard qw(ArrayRef Int);
use Test::More;
signature_for weakest_row => (
method => 0,
positional => [ ArrayRef[ ArrayRef[Int] ] ],
);
sub weakest_row ($matrix) {
my @row_strength = map {
my $ones = scalar grep { $_ == 1 } @{ $matrix->[$_] };
[ $ones, $_ ];
} 0 .. $#$matrix;
@row_strength = sort { $a->[0] <=> $b->[0] || $a->[1] <=> $b->[1] } @row_strength;
return [ map { $_->[1] } @row_strength ];
}
ch-2.py)def weakest_row(matrix: list[list[int]]) -> list[int]:
"""Return row indices sorted from weakest to strongest."""
row_strength: list[tuple[int, int]] = [
(sum(row), index) for index, row in enumerate(matrix)
]
row_strength.sort()
return [index for _, index in row_strength]