Peter’s blog ✴ Week 327 ✴ 23 June 2025

THE WEEKLY CHALLENGE
Missing and mad

The Perl Camel

Task 1

Missing integers

You are given an array of n integers. Write a script to find all the missing integers in the range 1..n in the given array.

Examples


Example 1
Input: @ints = (1, 2, 1, 3, 2, 5)
Output: (4, 6)
The given array has 6 elements.
So we are looking for integers in the range 1..6 in the 
   given array.
The missing integers: (4, 6)

Example 2
Input: @ints = (1, 1, 1)
Output: (2, 3)

Example 3
Input: @ints = (2, 2, 1)
Output: (3)

Analysis

This can be done in two steps:

  1. Create an array @present such that $present[$j] is defined if $j is present in the input array.
  2. Push the undefined indices of @present onto the output array.

Could this be done in a single line of Perl? Very likely, but I think that would be even harder to decipher so I'm sticking with my 2-line solution.

Perl Weekly’s review

from PW issue 727

Both solutions are clean, efficient, and well-documented. It prioritises readability over one-liners—a good choice for maintainability.

This review may cover either or both challenges for this week.

I am sorry that the 'Try it' feature is currently working very slowly or not at all owing to some issue with my web hosting provider.

Try it 

Try running the script with any input:



example: 3, 1, 4, 1, 5, 9

Script


#!/usr/bin/perl

# Blog: http://ccgi.campbellsmiths.force9.co.uk/challenge

use v5.26;    # The Weekly Challenge - 2025-06-23
use utf8;     # Week 327 - task 1 - Missing integers
use warnings; # Peter Campbell Smith
binmode STDOUT, ':utf8';
use Encode;

missing_integers(1, 2, 1, 3, 2, 5);
missing_integers(1, 1, 1);
missing_integers(2, 2, 1);
missing_integers(7, 8, 9);
missing_integers(5, 5, 5, 5, 5);
missing_integers(5, 4, 3, 2, 1);

sub missing_integers {
    
    my (@ints, @present, @absent);
    
    # initialise
    @ints = @_;
    
    # set $present[$j] to 1 if $j is present in @ints
    $present[$ints[$_]] = defined $ints[$_] ? 1 : 0 for 0 .. $#ints;
    
    # push $j onto @absent if $present[$j] is not defined
    push @absent, grep {not defined $present[$_]} 1 .. scalar @ints;
    
    # report results
    say qq[\nInput:  (] . join(', ', @ints) . q[)];
    say qq[Output: (] . join(', ', @absent) . q[)];
}

7 lines of code

Output from script


Input:  (1, 2, 1, 3, 2, 5)
Output: (4, 6)

Input:  (1, 1, 1)
Output: (2, 3)

Input:  (2, 2, 1)
Output: (3)

Input:  (7, 8, 9)
Output: (1, 2, 3)

Input:  (5, 5, 5, 5, 5)
Output: (1, 2, 3, 4)

Input:  (5, 4, 3, 2, 1)
Output: ()

 

Any content of this website which has been created by Peter Campbell Smith is in the public domain