Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
Find Equivalent Value and Frequency in Array in JavaScript
We are required to write a JavaScript function that takes in an array of integers as the only argument.
The function should check whether there exists an integer in the array such that its frequency is same as its value.
If there exists at least one such integer, we should return that integer otherwise we should return -1.
For example −
If the input array is −
const arr = [3, 4, 3, 8, 4, 9, 7, 4, 2, 4];
Then the output should be −
4
The value 4 appears 4 times in the array, so its frequency equals its value.
How It Works
The solution involves two steps:
- Count the frequency of each element using a frequency map
- Check if any element's value equals its frequency
Example
Following is the code −
const arr = [3, 4, 3, 8, 4, 9, 7, 4, 2, 4];
const checkValueFrequency = (arr = []) => {
const map = {};
// Count frequency of each element
for(let i = 0; i < arr.length; i++){
const el = arr[i];
map[el] = (map[el] || 0) + 1;
}
// Check if any value equals its frequency
for(key in map){
if(+key === map[key]){
return +key;
}
}
return -1;
};
console.log(checkValueFrequency(arr));
4
Alternative Approach Using Map
Here's a modern approach using the Map object:
const arr = [3, 4, 3, 8, 4, 9, 7, 4, 2, 4];
const checkValueFrequencyMap = (arr = []) => {
const freqMap = new Map();
// Count frequencies
for(const num of arr) {
freqMap.set(num, (freqMap.get(num) || 0) + 1);
}
// Find value equal to frequency
for(const [value, frequency] of freqMap) {
if(value === frequency) {
return value;
}
}
return -1;
};
console.log(checkValueFrequencyMap(arr));
4
Testing with Different Arrays
// Test case 1: Multiple matches
const arr1 = [1, 2, 2, 3, 3, 3];
console.log("Array 1:", checkValueFrequency(arr1)); // Returns 1, 2, or 3
// Test case 2: No matches
const arr2 = [5, 5, 5, 5, 5];
console.log("Array 2:", checkValueFrequency(arr2)); // Returns -1
// Test case 3: Single element
const arr3 = [1];
console.log("Array 3:", checkValueFrequency(arr3)); // Returns 1
Array 1: 1 Array 2: -1 Array 3: 1
Key Points
- The function returns the first match found, not all matches
- Time complexity: O(n) for counting + O(n) for checking = O(n)
- Space complexity: O(n) for the frequency map
- The `+key` conversion ensures we compare numbers, not strings
Conclusion
This problem efficiently uses frequency mapping to find elements whose value matches their occurrence count. The solution has linear time complexity and works well for finding value-frequency equivalence in arrays.
