The Weekly Challenge 327

Missing Integers & Minimum Absolute Difference!

Original Challenge Link

Task 1: Missing Integers

"Finding the Gaps: Identifying Missing Range Members!"

Given an array of n integers, identify all integers in the range 1..n that are not present in the array.

The Strategy: First, determine the size n of the array. Store the elements of the array in a set or hash for O(1) lookup. Then, iterate through the numbers from 1 to n and collect those that are not present in the set.
Perl Implementation
sub missing_integers {
    my (@ints) = @_;
    my $n = scalar @ints;
    my %present;
    $present{$_} = 1 for @ints;
    return [ grep { !$present{$_} } 1 .. $n ];
}
Python Implementation
def missing_integers(ints: list[int]) -> list[int]:
    n = len(ints)
    present = set(ints)
    return [i for i in range(1, n + 1) if i not in present]

Task 2: MAD (Minimum Absolute Difference)

"Minimum Gaps: Locating Pairs with the MAD!"

Given an array of distinct integers, find all pairs that have the minimum absolute difference.

The Strategy: Sort the array first. Sorting ensures that the minimum difference must occur between adjacent elements. Iterate through the sorted array, calculating the difference between each pair of neighbors. Keep track of the minimum difference found and store all pairs that match this minimum.
Perl Implementation
sub mad_pairs {
    my (@ints) = @_;
    return [] if @ints < 2;
    my @sorted = sort { $a <=> $b } @ints;
    my $min = 'inf';
    my @pairs;
    for my $i (1 .. $#sorted) {
        my $diff = $sorted[$i] - $sorted[$i - 1];
        if ($diff < $min) {
            $min = $diff;
            @pairs = ([ $sorted[$i - 1], $sorted[$i] ]);
        } elsif ($diff == $min) {
            push @pairs, [ $sorted[$i - 1], $sorted[$i] ];
        }
    }
    return \@pairs;
}
Python Implementation
def mad_pairs(ints: list[int]) -> list[tuple[int, int]]:
    if len(ints) < 2:
        return []
    sorted_ints = sorted(ints)
    min_diff = float("inf")
    result = []
    for a, b in zip(sorted_ints, sorted_ints[1:]):
        diff = b - a
        if diff < min_diff:
            min_diff = diff
            result = [(a, b)]
        elif diff == min_diff:
            result.append((a, b))
    return result