1 #!/usr/bin/perl
 2 # https://theweeklychallenge.org/blog/perl-weekly-challenge-208/#TASK2
 3 #
 4 # Task 2: Duplicate and Missing
 5 # =============================
 6 #
 7 # You are given an array of integers in sequence with one missing and one duplicate.
 8 #
 9 # Write a script to find the duplicate and missing integer in the given array. Return -1 if none found.
10 #
11 # For the sake of this task, let us assume the array contains no more than one duplicate and missing.
12 #
13 ## Example 1:
14 ##
15 ## Input: @nums = (1,2,2,4)
16 ## Output: (2,3)
17 ##
18 ## Duplicate is 2 and Missing is 3.
19 #
20 ## Example 2:
21 ##
22 ## Input: @nums = (1,2,3,4)
23 ## Output: -1
24 ##
25 ## No duplicate and missing found.
26 #
27 ## Example 3:
28 ##
29 ## Input: @nums = (1,2,3,3)
30 ## Output: (3,4)
31 ##
32 ## Duplicate is 3 and Missing is 4.
33 #
34 ############################################################
35 ##
36 ## discussion
37 ##
38 ############################################################
39 #
40 # Walk the array, keep track of the previous element, and
41 # check where we're at with the current one.
42 
43 use strict;
44 use warnings;
45 
46 duplicate_and_missing(1,2,2,4);
47 duplicate_and_missing(1,2,3,4);
48 duplicate_and_missing(1,2,3,3);
49 
50 sub duplicate_and_missing {
51    my @nums = @_;
52    my $duplicate;
53    my $missing;
54    print "Input: (" . join(",", @nums) . ")\n";
55    my $last_element = shift @nums;
56    foreach my $element (@nums) {
57       if($element == $last_element) {
58          $duplicate = $element;
59          $missing = $element+1;
60       } elsif ($element > $last_element+1) {
61          $missing = $last_element+1;
62       }
63       $last_element = $element;
64    }
65    if(defined($duplicate) && defined($missing)) {
66       print "Output: ($duplicate, $missing)\n";
67    } else {
68       print "Output: -1\n";
69    }
70 }