Task 1: Min Abs Diff
"Closest Pairs: Finding the Smallest Gaps!"
This week's first task involves finding pairs of elements with the minimum absolute difference. Given an array of distinct integers, we need to find all pairs [a, b] where a < b and b - a equals the minimum absolute difference among all element pairs in the array.
The Strategy: First, we sort the array. The minimum absolute difference must occur between adjacent elements in the sorted array. We find the minimum difference by comparing adjacent elements, then collect all adjacent pairs that achieve this minimum difference. This approach is efficient with O(n log n) time complexity.
Perl Implementation
sub min_abs_diff_pairs ($ints) {
($ints) = $LIST_CHECK->($ints);
return [] if @$ints < 2;
my @sorted = sort { $a <=> $b } @$ints;
my $min_diff = undef;
for my $i ( 1 .. $#sorted ) {
my $diff = $sorted[$i] - $sorted[ $i - 1 ];
$min_diff = $diff if !defined($min_diff) || $diff < $min_diff;
}
my @pairs;
for my $i ( 1 .. $#sorted ) {
my $diff = $sorted[$i] - $sorted[ $i - 1 ];
push @pairs, [ $sorted[ $i - 1 ], $sorted[$i] ] if $diff == $min_diff;
}
return \\@pairs;
}
Python Implementation
def min_abs_diff_pairs(ints: Sequence[int]) -> list[tuple[int, int]]:
"""Return all (a, b) pairs with minimum absolute difference (a < b)."""
if len(ints) < 2:
return []
sorted_ints = sorted(ints)
min_diff = min(sorted_ints[i] - sorted_ints[i - 1] for i in range(1, len(sorted_ints)))
return [
(sorted_ints[i - 1], sorted_ints[i])
for i in range(1, len(sorted_ints))
if sorted_ints[i] - sorted_ints[i - 1] == min_diff
]