Uneven number
and binary tree
Weekly challenge 130 — 13 September 2021
Week 130: 13 Sep 2021
You are given an array of positive integers, such that all the numbers appear even number of times except one number. Write a script to find that integer.
Example 1 Input: @N = (2, 5, 4, 4, 5, 5, 2) Output: 5 as it appears 3 times in the array whereas all other numbers - 2 and 4 - appear exactly twice. Example 2 Input: @N = (1, 2, 3, 4, 3, 2, 1, 4, 4) Output: 4
My vanilla solution is to pass through the array counting the number of occurrences of each entry, and then pass through the array of counts until finding an odd number.
#!/usr/bin/perl use v5.26; use strict; use warnings; # PWC 130 task 1 - Peter Campbell Smith - 2021-09-13 my (@N, $j, %count); # sample data (3 is the answer) @N = (1, 2, 3, 4, 3, 2, 1, 4, 4, 3, 4); # get $count{$j} == number of instances of $j for $j (@N) { $count{$j}++; } # look for the first instance of $count{$j} being odd for $j (keys %count) { if ($count{$j} & 1) { say qq[\nInput: ] . join(', ', @N); say qq[Output: $j]; last; } }
Input: 1, 2, 3, 4, 3, 2, 1, 4, 4, 3, 4 Output: 3
Any content of this website which has been created by Peter Campbell Smith is in the public domain