This piece of code returns the indices of array whose values add up to a target "sum". It handles unsorted array with duplicate entries.
In Perl with 0(n) time complexity using hash map:
#!/usr/bin/perl
use strict;
use warnings;
use Data::Dumper;
my @array=(41,7,2,3,4,6,1,10);
#lets assume we want 2 indexes from the above array
#which will add up to sum 10
my $sum = 10;
my ($idx1, $idx2); # these are the indexes
my $i = 0;
#convert the array into hash with keys starting from 0 and
#array elements stored as values
my %my_hash = map {$i++ => $_}@array;
print Dumper \%my_hash;
# create a reverse hash to retrieve keys from values
my %rhash = reverse %my_hash;
#iterate through the first hash, we need to make sure the
#hash is sorted so that the hash keys match with array index order
for my $key (sort keys %my_hash) {
#this is to store the second value which adds
#to first value $my_hash{$key} to be equal to sum
my $second_val = $sum-$my_hash{$key};
#if the second key exists in reverse hash, we
#can easily find the index
if (defined $rhash{$second_val}) {
$idx1= $key;
$idx2= $rhash{$second_val};
print "Indexes are $idx1 $idx2\n";
}
}