Task 1: Peak Positions
"Spotting the Summits: Where Are the Peaks?"
Given an array of integers, find all peaks — elements that are strictly greater than both their left and right neighbours. Return the indices of all such positions.
The Strategy: Iterate once over the array. For each index, compare the element with its left neighbour (if any) and right neighbour (if any). An element qualifies as a peak only when it is strictly greater than both. The first and last elements can also be peaks if they exceed their single neighbour.
Perl Implementation
sub peak_positions ($ints_ref) {
state $check = compile( ArrayRef [Int] );
my ($ints) = $check->($ints_ref);
my @peaks;
for my $idx ( 0 .. $#$ints ) {
my $current = $ints->[$idx];
my $left = $idx > 0 ? $ints->[ $idx - 1 ] : undef;
my $right = $idx < $#$ints ? $ints->[ $idx + 1 ] : undef;
next if defined($left) && $current <= $left;
next if defined($right) && $current <= $right;
push @peaks, $idx;
}
return \@peaks;
}
Python Implementation
def peak_positions(ints: list[int]) -> list[int]:
"""Return indices of all elements strictly greater than their neighbours."""
peaks = []
for i, val in enumerate(ints):
left = ints[i - 1] if i > 0 else None
right = ints[i + 1] if i < len(ints) - 1 else None
if left is not None and val <= left:
continue
if right is not None and val <= right:
continue
peaks.append(i)
return peaks