The Weekly Challenge 334

Subarray Sums & Manhattan Proximity!

Original Challenge Link

Task 1: Range Sum

"Slice and Sum: What's Between the Indices?"

Given an array of integers and two indices x and y, return the sum of all elements between those indices inclusive.

The Strategy: Validate that x is not greater than y and both are within bounds. Then sum elements from index x to y inclusive. Simple linear scan over the subarray.
Perl Implementation
sub range_sum {
    my ( $ints, $x, $y ) = @_;
    return 0 unless @$ints && $x <= $y && $x >= 0 && $y < @$ints;

    my $sum = 0;
    $sum += $ints->[$_] for $x .. $y;
    return $sum;
}
Python Implementation
def range_sum(ints: list[int], x: int, y: int) -> int:
    """Sum of elements from index x to y inclusive."""
    if not ints or x > y or x < 0 or y >= len(ints):
        return 0
    return sum(ints[x:y+1])

Task 2: Nearest Valid Point

"Share a Line: Find the Closest Matching Point!"

Given a point (x, y) and a list of points, find the index of the valid point (sharing the same x or y coordinate) with the smallest Manhattan distance. Return -1 if no valid points exist.

The Strategy: Iterate through all points. A point is valid if it shares x or y with the given location. Among valid points, pick the one with the smallest Manhattan distance |dx| + |dy|.
Perl Implementation
sub nearest_valid_point {
    my ( $x, $y, $points ) = @_;

    my $min_distance = undef;
    my $min_index    = -1;

    for my $i ( 0 .. @$points - 1 ) {
        my ( $px, $py ) = @{ $points->[$i] };
        next unless $px == $x || $py == $y;

        my $distance = abs( $px - $x ) + abs( $py - $y );
        if ( !defined $min_distance || $distance < $min_distance ) {
            $min_distance = $distance;
            $min_index    = $i;
        }
    }

    return $min_index;
}
Python Implementation
def nearest_valid_point(x: int, y: int, points: list[list[int]]) -> int:
    """Index of closest valid point (sharing x or y), or -1."""
    best = -1
    best_dist = None

    for i, (px, py) in enumerate(points):
        if px != x and py != y:
            continue
        dist = abs(px - x) + abs(py - y)
        if best_dist is None or dist < best_dist:
            best_dist = dist
            best = i

    return best