The Weekly Challenge 337

Element Comparison & Matrix Flipping!

Original Challenge Link

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))
    ]

Task 2: Odd Matrix

"Increment Rows and Columns: Count the Odd Cells!"

Given a matrix of size row x col and a list of locations, increment all cells in the row and column of each location, then count how many cells end up with odd values.

The Strategy: Initialize a matrix of zeros. For each location (r, c), increment all cells in row r and column c. Then count cells with odd values. A cell at (i, j) ends up odd when the number of times its row and column were touched is odd.
Perl Implementation
sub odd_matrix {
    my ( $row, $col, $locations ) = @_;
    my @matrix;

    for my $i ( 0 .. $row - 1 ) {
        for my $j ( 0 .. $col - 1 ) {
            $matrix[$i][$j] = 0;
        }
    }

    for my $loc (@$locations) {
        my ( $r, $c ) = @$loc;
        for my $i ( 0 .. $col - 1 ) { $matrix[$r][$i]++; }
        for my $i ( 0 .. $row - 1 ) { $matrix[$i][$c]++; }
    }

    my $odd_cells = 0;
    for my $i ( 0 .. $row - 1 ) {
        for my $j ( 0 .. $col - 1 ) {
            $odd_cells++ if $matrix[$i][$j] % 2 != 0;
        }
    }

    return $odd_cells;
}
Python Implementation
def odd_matrix(row: int, col: int, locations: list[list[int]]) -> int:
    """Increment row/col at each location; count odd-valued cells."""
    matrix = [[0] * col for _ in range(row)]

    for r, c in locations:
        for j in range(col):
            matrix[r][j] += 1
        for i in range(row):
            matrix[i][c] += 1

    return sum(1 for i in range(row) for j in range(col) if matrix[i][j] % 2)