Task 1: Unique Occurrences
You are given an array of integers, @ints.
Write a script to return 1 if the number of occurrences of each value in the given array is unique or 0 otherwise.
Example 1: Input: @ints = (1, 2, 2, 1, 1, 3) → Output: 1 (1 occurs 3 times, 2 occurs 2 times, 3 occurs 1 time)
Example 2: Input: @ints = (1, 2, 3) → Output: 0
Example 3: Input: @ints = (-2, 0, 1, -2, 1, 1, 0, 1, -2, 9) → Output: 1
Method Explanation
We solve the problem in two passes:
- Count the occurrences (frequency) of each distinct integer in
@intsusing a hash table (%countin Perl orcollections.Counterin Python). - Verify that all frequency values are mutually distinct by checking whether the number of distinct frequencies equals the number of distinct integers.
Both steps run in $O(N)$ time and $O(N)$ auxiliary space.
Perl Solution
use v5.38;
use warnings;
use Type::Params -sigs;
use Types::Standard qw(ArrayRef Int);
signature_for unique_occurrences => (
method => 0,
positional => [ ArrayRef [Int] ],
);
sub unique_occurrences ($ints) {
my %count;
$count{$_}++ for @$ints;
my %occurrences_count;
for my $freq ( values %count ) {
return 0 if $occurrences_count{$freq}++;
}
return 1;
}
Python Solution
from collections import Counter
def unique_occurrences(ints: list[int]) -> int:
"""Return 1 if the number of occurrences of each value in ints is unique, else 0."""
counts = Counter(ints).values()
return 1 if len(counts) == len(set(counts)) else 0