Remove elements that appear strictly less than k times

Given an array of integers, remove all the elements which appear strictly less than k times.

Examples:

Input : arr[] = {1, 2, 2, 3, 2, 3, 4}
        k = 2
Output : 2 2 3 2 3
Explanation : {1, 4} appears less than 2 times.


Approach :

  • Take a hash map, which will store the frequency of all the elements in the array.
  • Now, traverse once again.
  • Remove the elements which appears strictly less than k times.
  • Else, print it.
filter_none

edit
close

play_arrow

link
brightness_4
code

// C++ program to remove the elements which
// appear strictly less than k times from the array.
#include "iostream"
#include "unordered_map"
using namespace std;
  
void removeElements(int arr[], int n, int k)
{
    // Hash map which will store the
    // frequency of the elements of the array.
    unordered_map<int, int> mp;
  
    for (int i = 0; i < n; ++i) {
        // Incrementing the frequency
        // of the element by 1.
        mp[arr[i]]++;
    }
  
    for (int i = 0; i < n; ++i) {
  
        // Print the element which appear
        // more than or equal to k times.
        if (mp[arr[i]] >= k) {
            cout << arr[i] << " ";
        }
    }
}
  
int main()
{
    int arr[] = { 1, 2, 2, 3, 2, 3, 4 };
    int n = sizeof(arr) / sizeof(arr[0]);
    int k = 2;
    removeElements(arr, n, k);
    return 0;
}

chevron_right


Output:

2 2 3 2 3

Time Complexity – O(N)



My Personal Notes arrow_drop_up

Check out this Author's contributed articles.

If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.

Please Improve this article if you find anything incorrect by clicking on the "Improve Article" button below.