Duplicate Items In An Array
June 14, 2016
Today’s exercise is in two parts, first a commonly-seen programming exercise and then a variant on it; the origin of the exercise is certainly someone’s homework, but since school is out for the year it doesn’t matter that we do the exercise today.
First, write a program that, given an array of integers in unsorted order, finds the single duplicate number in the array. For instance, given the input [1,2,3,1,4], the correct output is 4.
Second, write a program that, given an array of integers in unsorted order, finds all of the multiple duplicate numbers in the array. For instance, given the input [1,2,3,1,2,4,1], the correct output is [1,2,1].
Your task is to write the two programs that find duplicates in an array. When you are finished, you are welcome to read or run a suggested solution, or to post your own solution or discuss the exercise in the comments below.
Pretty much 1-liners for both of these in Perl – using core perl (+List::Util)
Part 1 – find (only) first entry…
Part 1 – find all entries
[sourceode lang=”perl”]
use feature qw(say);
say join q( ), grep { exists $X{$_} || !($X{$_}=1) } @ARGV;
[/sourcecode]
If the numbers are bounded and small, you can use a bit vector, which takes less actual space than a hash table.
Here’s a solution in C. It uses GLib for its hash table.
Here’s the output:
The problem says “the correct output is 4”. I should seemingly say 1 (there’s only one 4, but there are two 1s).
A Haskell version, favouring conciseness over efficiency.
Incidentally, the first part has been an exercise on here before (albeit with an upper bound on the array elements) way back in 2011. https://programmingpraxis.com/2011/09/23/array-duplicates/
A good problem