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, and my $target = 9 stores the target as a scalar.
  • my %seen is 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, @arr is 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 like 2 are looked up consistently by their string form.
  • On a miss, $seen{$value} = $i records the current value's zero-based index.
  • The trace first checks value 2, needs 7, misses, and records %seen as {2: 0}.
  • At i = 1, value 7 needs 2; exists $seen{2} hits, so $first becomes 0 and $second becomes 1.
  • last stops the loop after the hit, so later values 11, 4, and 5 are 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.