DEV Community

Discussion on: Daily Challenge #63- Two Sum

Collapse
 
choroba profile image
E. Choroba

Perl solution. Walk the array, for each element, store the expected counterpart into a hash. If the element already exists in the hash, we have the pair.

#!/usr/bin/perl
use warnings;
use strict;

sub two_sum {
    my ($arr, $sum) = @_;
    my %expect;
    for my $i (0 .. $#$arr) {
        return [ $expect{ $sum - $arr->[$i] }, $i ]
            if exists $expect{ $sum - $arr->[$i] };
        $expect{ $arr->[$i] } = $i;
    }
}

use Test::More tests => 2;
is_deeply two_sum([1, 2, 3], 4), [0, 2];
is_deeply two_sum([1 .. 99], 197), [97, 98];