|
| 1 | +# 1207. Unique Number of Occurrences |
| 2 | +# 🟢 Easy |
| 3 | +# |
| 4 | +# https://leetcode.com/problems/unique-number-of-occurrences/ |
| 5 | +# |
| 6 | +# Tags: Array |
| 7 | + |
| 8 | +import timeit |
| 9 | +from collections import Counter |
| 10 | +from typing import List |
| 11 | + |
| 12 | + |
| 13 | +# A fast solution is to use Collections.Counter to get the count of |
| 14 | +# occurrences of each value, then check if the count of unique values |
| 15 | +# equals the total number of values, for example using a set. |
| 16 | +# |
| 17 | +# Time complexity: O(n) |
| 18 | +# Space complexity: O(m) - Where m is the number of unique values in the |
| 19 | +# input. |
| 20 | +# |
| 21 | +# Runtime: 39 ms, faster than 91.14% |
| 22 | +# Memory Usage: 14 MB, less than 72.74% |
| 23 | +class Solution: |
| 24 | + def uniqueOccurrences(self, arr: List[int]) -> bool: |
| 25 | + c = Counter(arr) |
| 26 | + return len(c) == len(set(c.values())) |
| 27 | + |
| 28 | + |
| 29 | +def test(): |
| 30 | + executors = [ |
| 31 | + Solution, |
| 32 | + ] |
| 33 | + tests = [ |
| 34 | + [[1, 2, 2, 1, 1, 3], True], |
| 35 | + [[1, 2], False], |
| 36 | + [[-3, 0, 1, -3, 1, 1, 1, -3, 10, 0], True], |
| 37 | + ] |
| 38 | + for executor in executors: |
| 39 | + start = timeit.default_timer() |
| 40 | + for _ in range(1): |
| 41 | + for col, t in enumerate(tests): |
| 42 | + sol = executor() |
| 43 | + result = sol.uniqueOccurrences(t[0]) |
| 44 | + exp = t[1] |
| 45 | + assert result == exp, ( |
| 46 | + f"\033[93m» {result} <> {exp}\033[91m for" |
| 47 | + + f" test {col} using \033[1m{executor.__name__}" |
| 48 | + ) |
| 49 | + stop = timeit.default_timer() |
| 50 | + used = str(round(stop - start, 5)) |
| 51 | + cols = "{0:20}{1:10}{2:10}" |
| 52 | + res = cols.format(executor.__name__, used, "seconds") |
| 53 | + print(f"\033[92m» {res}\033[0m") |
| 54 | + |
| 55 | + |
| 56 | +test() |
0 commit comments