Find the element with k frequency in an array

Learn how to find the element with k frequency in an array.

Given an array of elements find an element which has occurred K times. If there are no such element then return -1.

Example

Input:
[2, 4, 4, 3, 3, 7, 7, 7, 8] 3
[1, 2, 3, 4, 4] 3
Output:
7
-1

In the first example 7 is only element with 3 counts so we returned it. While in the second example there are no elements with 3 frequency so we returned -1.

Program to find the element with k frequency in an array

There are two ways to solve this problem.

  1. We use nested loops and find the element with given frequency, It works in O(n ^ 2).
  2. We store the count of each element using an Hashmap and the return the element with given k frequency from the hashmap. This one is an efficient approach and works in O(n) time.

Implementation

  • Using the array reduce method we count the frequency of each element.
  • And then iterate over all the entries of hashmap and return the element with k frequency if present, else return -1.
const elementWithKFrequency = (arr, k) => {
    //Store the number counts in object
    const count = arr.reduce((a, b) => {
        if (!a[b]) {
        a[b] = 1;
        } else {
        a[b]++;
        }

        return a;
    }, {});

    //Find the number with k count
    for (const [key, value] of Object.entries(count)) {
        if (value === k) {
        return key;
        }
    }

    return -1;
};
Input:
console.log(elementWithKFrequency([1, 1, 1, 2, 2, 2, 3, 3, 4], 2));
console.log( elementWithKFrequency([2, 2, 2, 3, 3, 3, 2, 5, 5, 5, 6, 6], 2));

Output:
3
6

Time complexity: O(n).
Space complexity: O(n).