The Weekly Challenge 343

Closest to Zero & Tournament Champions!

Original Challenge Link

Task 1: Zero Friend

"Nearest Neighbour: Who's Closest to Zero?"

Given an array of integers, find the number closest to zero and return its absolute distance from zero. If there are ties, return the smaller absolute value.

The Strategy: Track the minimum absolute value seen while scanning the array once. Return 0 if any element is exactly zero. Otherwise return the smallest absolute value found.
Perl Implementation
sub zero_friend : prototype(@) (@nums) {
    return 0 unless @nums;

    my $min_distance = abs( $nums[0] );
    for my $num (@nums) {
        my $distance = abs($num);
        $min_distance = $distance if $distance < $min_distance;
    }

    return $min_distance;
}
Python Implementation
def zero_friend(nums: list[int]) -> int:
    """Return the absolute distance of the number closest to zero."""
    if not nums:
        return 0
    return min(abs(x) for x in nums)

Task 2: Champion Team

"Tournament Grid: Who's the Strongest?"

Given a grid where grid[i][j] = 1 means team i beats team j, find the champion. The champion has the most wins, or if tied, beats all other top teams.

The Strategy: Count wins for each team from the grid. Find the maximum win count. Among teams with that maximum, check which one beats all others in the top group. Return that team.
Perl Implementation
sub champion_team : prototype(@) (@grid) {
    my $n = @grid;
    return -1 unless $n;

    my @wins = (0) x $n;
    for my $i ( 0 .. $n - 1 ) {
        for my $j ( 0 .. $n - 1 ) {
            $wins[$i] += $grid[$i][$j] if $i != $j;
        }
    }

    my $max_wins = 0;
    for my $win (@wins) {
        $max_wins = $win if $win > $max_wins;
    }

    my @top_teams;
    for my $i ( 0 .. $n - 1 ) {
        push @top_teams, $i if $wins[$i] == $max_wins;
    }

    return "Team $top_teams[0]" if @top_teams == 1;

    for my $i (@top_teams) {
        my $is_champion = 1;
        for my $j (@top_teams) {
            next if $i == $j;
            unless ( $grid[$i][$j] ) {
                $is_champion = 0;
                last;
            }
        }
        return "Team $i" if $is_champion;
    }

    return "Team $top_teams[0]";
}
Python Implementation
def champion_team(grid: list[list[int]]) -> str:
    """Find the team that is the tournament champion."""
    n = len(grid)
    if n == 0:
        return "-1"

    wins = [0] * n
    for i in range(n):
        for j in range(n):
            if i != j:
                wins[i] += grid[i][j]

    max_wins = max(wins)
    top = [i for i, w in enumerate(wins) if w == max_wins]

    if len(top) == 1:
        return f"Team {top[0]}"

    for i in top:
        if all(grid[i][j] for j in top if j != i):
            return f"Team {i}"

    return f"Team {top[0]}"