Smallest element repeated exactly ‘k’ times (not limited to small range)

link 0

Given an array of size n, the goal is to find out the smallest number that is repeated exactly ‘k’ times where k > 0?
And

Examples:

Input : a[] = {2, 1, 3, 1, 2, 2}
        k = 3
Output : 2

Input : a[] = {3, 4, 3, 2, 1, 5, 5} 
        k = 2
Output : 3
Explanation: As 3 is smaller than 5. 
So 3 should be printed.

 

The solutions discussed above are either limited to small range work in more than linear time. In this post a hashing based solution is discussed that works in O(n) time and is applicable to any range. Below are abstract steps.

1) Create a hash map that stores elements and their frequencies.
2) Traverse given array. For every element being traversed, increment its frequency.
3) Traverse hash map and print the smallest element with frequency k.

// C++ program to find the smallest element
// with frequency exactly k.
#include <bits/stdc++.h>
using namespace std;
int smallestKFreq(int a[], int n, int k)
{
    unordered_map<int, int> m;
    // Map is used to store the count of
    // elements present in the array
    for (int i = 0; i < n; i++)
        m[a[i]]++;
    // Traverse the map and find minimum
    // element with frequency k.
    int res = INT_MAX;
    for (auto it = m.begin(); it != m.end(); ++it)
        if (it->second == k)
           res = min(res, it->first);
    return (res != INT_MAX)? res : -1;
}
// Driver code
int main()
{
    int arr[] = { 2, 2, 1, 3, 1 };
    int k = 2;
    int n = sizeof(arr) / (sizeof(arr[0]));
    cout << smallestKFreq(arr, n, k);
    return 0;
}

Output:

1

Time Complexity : O(n)
Auxiliary Space : O(n)

 

Disclaimer: This content belongs to geeksforgeeks, source: http://geeksforgeeks.org

rakesh

Leave a Reply

Your email address will not be published. Required fields are marked *

Skip to toolbar