Given a list of integers nums, return whether there’s an integer whose frequency in the list is same as its value.
Constraints
n ≤ 100,000 where n is the length of nums
Example 1
Input
nums = [7, 9, 3, 3, 3]
Output
true
Explanation
The number 3 appears 3 times.
C++ Hash Table to Find Equivalent Value and Frequency in Array
Let’s use a O(N) hash table store the numbers and their frequencies, and the second pass we can check the elements in the hash table to see if the item has same value and frequency.
1 2 3 4 5 6 7 8 | bool equivalentValueAndFrequency(vector<int>& nums) { unordered_map<int, int> data; for (auto &n: nums) data[n] ++; for (auto &[a, b]: data) { if (a == b) return true; } return false; } |
bool equivalentValueAndFrequency(vector<int>& nums) { unordered_map<int, int> data; for (auto &n: nums) data[n] ++; for (auto &[a, b]: data) { if (a == b) return true; } return false; }
Find Equivalent Value and Frequency in Array in Python
In Python, we can count the frequency using Counter(data).
1 2 3 4 5 6 7 | class Solution: def equivalentValueAndFrequency(self, nums): data = Counter(nums) for i in data.keys(): if i == data[i]: return True return False |
class Solution: def equivalentValueAndFrequency(self, nums): data = Counter(nums) for i in data.keys(): if i == data[i]: return True return False
A more Pythonic way of checking using list comprehension:
1 2 3 4 | class Solution: def equivalentValueAndFrequency(self, nums): counts = Counter(nums) return any(k == v for k, v in counts.items()) |
class Solution: def equivalentValueAndFrequency(self, nums): counts = Counter(nums) return any(k == v for k, v in counts.items())
–EOF (The Ultimate Computing & Technology Blog) —
GD Star Rating
loading...
306 wordsloading...
Last Post: Teaching Kids Programming - Introduction to Trees, Binary Trees, Perfect Binary Trees, and BFS.
Next Post: Teaching Kids Programming - Different Algorithms to Check if a String is Palindrome