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];
Are you sure you want to hide this comment? It will become hidden in your post, but will still be visible via the comment's permalink.
Hide child comments as well
Confirm
For further actions, you may consider blocking this person and/or reporting abuse
We're a place where coders share, stay up-to-date and grow their careers.
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.