Arrays and Iteration
Two-Sum with Hash Lookup
Walk the array once, storing seen values in a lookup table. When the complement is already present, the result indices are known.
Algorithm
Basic Implementation
basic.pl
use strict;
use warnings;
my @arr = (2, 7, 11, 4, 5);
my $target = 9;
my %seen;
my ($first, $second) = (-1, -1);
for (my $i = 0; $i < @arr; $i++) {
my $value = $arr[$i];
my $need = $target - $value;
if (exists $seen{$need}) {
$first = $seen{$need};
$second = $i;
last;
}
$seen{$value} = $i;
}
print "[$first, $second]\n";
Complexity
- Time: O(n) average
- Space: O(n)
Implementation notes
my @arr = (2, 7, 11, 4, 5)declares the pinned input array with the@sigil, andmy $target = 9stores the target as a scalar.my %seenis the Perl hash used as the lookup table; hash variables use the%sigil.my ($first, $second) = (-1, -1)sets the fallback result before the scan.- The loop is indexed:
for (my $i = 0; $i < @arr; $i++). In the loop bound,@arris in scalar context, so it means the array length. - Each element is read with scalar element syntax,
my $value = $arr[$i]. - The complement is numeric subtraction:
my $need = $target - $value. exists $seen{$need}checks whether the needed value has already been recorded; Perl hash keys are stored as strings internally, so numeric keys like2are looked up consistently by their string form.- On a miss,
$seen{$value} = $irecords the current value's zero-based index. - The trace first checks value
2, needs7, misses, and records%seenas{2: 0}. - At
i = 1, value7needs2;exists $seen{2}hits, so$firstbecomes0and$secondbecomes1. laststops the loop after the hit, so later values11,4, and5are not scanned in this replay.print "[$first, $second]\n"interpolates the two scalar indices and prints[0, 1].
execution replay
The checked-in replay follows the language-neutral state table for `array-two-sum-hash`.
cross-language comparison
This Perl DSA version keeps the same data and final output as every other DSA book in this wave.