Monday, October 27, 2025

TWC345

Challenge Link

Task1

We traverse the array by steps of 3 elements each time and test for the peak element:
#!/usr/bin/env perl
use strict;
use warnings;
use Data::Show;

sub peak_positions{
  my ($arr) = @_;
  my @res;
  foreach my $i(1..$#$arr) {
    if($arr->[$i-1] < $arr->[$i] && $arr->[$i+1] < $arr->[$i]) {
      push @res,$i
    }
  }
  @res
}

show peak_positions([1,3,2]);
show peak_positions([2,4,6,5,3]);
show peak_positions([1,2,3,2,4,1]);
show peak_positions([5,3,1]);
show peak_positions([1,5,1,5,1,5,1]);

Task2

We simulate the operations while traversing the array:
#!/usr/bin/env perl
use strict;
use warnings;
use Data::Show;

sub last_visitor{
  my ($arr) = @_;
  my (@res,@seen);
  my $k = 0;
  foreach my $i(0..$#$arr) {
    if($arr->[$i] != -1) {
      push @seen,$arr->[$i];
      $k = @seen
    } elsif ($k == 0) {
      push @res,-1
    } else {
      push @res,$seen[--$k]
    }
  }
  @res
}

show last_visitor([5,-1,-1]);
show last_visitor([3,7,-1,-1,-1]);
show last_visitor([2,-1,4,-1,-1]);
show last_visitor([10,20,-1,30,-1,-1]);
show last_visitor([-1,-1,5,-1])

0 comments:

Post a Comment