Find the first input value whose final frequency is one.

Algorithm

Canonical input [3, 5, 2, 5, 3, 8, 2] prints 8. The replay uses the same input in every language, so this Perl DSA implementation can be compared directly with the rest of the DSA track.

Basic Implementation

basic.pl
use strict;
use warnings;

my @arr = (3, 5, 2, 5, 3, 8, 2);
my %count;
for my $value (@arr) {
    $count{$value} += 1;
}
for my $value (@arr) {
    if ($count{$value} == 1) {
        print "$value\n";
        last;
    }
}

Complexity

  • Time: O(n) average
  • Space: O(k) for k distinct values

Implementation notes

  • The checked input is numeric, not characters: my @arr = (3, 5, 2, 5, 3, 8, 2).
  • my %count declares the Perl hash table with the % sigil.
  • The first pass is for my $value (@arr), so values are counted in input order.
  • Count updates use $count{$value} += 1; the first write creates that hash entry, then later writes increment the stored number.
  • Perl hash keys are strings internally, but numeric keys like 3, 5, 2, and 8 are looked up consistently through $count{$value}.
  • The count trace starts at {}, then records {3: 1}, {3: 1, 5: 1}, and {3: 1, 5: 1, 2: 1}.
  • Repeated values update the same hash entries: the final count table is {3: 2, 5: 2, 2: 2, 8: 1}.
  • The second pass also uses for my $value (@arr), so the first-non-repeating decision follows the original array order, not hash iteration order.
  • The condition is numeric: if ($count{$value} == 1).
  • The trace checks 3, 5, 2, 5, and 3; each has frequency 2, so no value is printed yet.
  • At array index 5, value 8 has frequency 1, so the code prints it and last stops the loop.
  • print "$value\n" interpolates the found scalar and outputs 8.
two-pass lookup The first pass builds a frequency table. The second pass keeps the original order and stops at the first value with frequency one.