Task 1: Smaller Than Current
"Count the Competition: How Many Are Less or Equal?"
Given an array of numbers, return an array where each element is the count of other numbers in the original array that are less than or equal to it (excluding itself).
The Strategy: For each element, count how many other elements (excluding itself) are less than or equal to it. A simple double-loop O(n^2) approach works well for small arrays.
Perl Implementation
sub smaller_than_current {
my (@nums) = @_;
my @result;
for my $i ( 0 .. $#nums ) {
my $count = 0;
for my $j ( 0 .. $#nums ) {
next if $i == $j;
if ( $nums[$j] <= $nums[$i] ) {
$count++;
}
}
push @result, $count;
}
return @result;
}
Python Implementation
def smaller_than_current(nums: list[int]) -> list[int]:
"""Count how many others are less than or equal to each element."""
return [
sum(1 for j, v in enumerate(nums) if j != i and v <= nums[i])
for i in range(len(nums))
]