Remove elements from the array which appear more than k times
Last Updated :
18 Jan, 2024
Given an array of integers, remove all the occurrences of those elements which appear strictly more than k times in the array.
Examples:
Input : arr[] = {1, 2, 2, 3, 2, 3, 4}
k = 2
Output : 1 3 3 4
Input : arr[] = {2, 5, 5, 7}
k = 1
Output : 2 7
Approach:
- Take a hash map, which will store the frequency of all the elements in the array.
- Now, traverse once again.
- Print the elements which appear less than or equal to k times.
C++
// C++ program to remove the elements which
// appear more 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
// less than or equal to k times.
if (mp[arr[i]] <= k) {
cout << arr[i] << " ";
}
}
}
int main(int argc, char const* argv[])
{
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;
}
Java
// Java program to remove the elements which
// appear more than k times from the array.
import java.util.HashMap;
import java.util.Map;
class GFG
{
static void RemoveElements(int arr[], int n, int k)
{
// Hash map which will store the
// frequency of the elements of the array.
Map<Integer,Integer> mp = new HashMap<>();
for (int i = 0; i < n; ++i)
{
// Incrementing the frequency
// of the element by 1.
mp.put(arr[i],mp.get(arr[i]) == null?1:mp.get(arr[i])+1);
}
for (int i = 0; i < n; ++i)
{
// Print the element which appear
// less than or equal to k times.
if (mp.containsKey(arr[i]) && mp.get(arr[i]) <= k)
{
System.out.print(arr[i] + " ");
}
}
}
// Driver code
public static void main(String[] args)
{
int arr[] = { 1, 2, 2, 3, 2, 3, 4 };
int n = arr.length;
int k = 2;
RemoveElements(arr, n, k);
}
}
// This code is contributed by Rajput-Ji
Python3
# Python 3 program to remove the elements which
# appear more than k times from the array.
def RemoveElements(arr, n, k):
# Hash map which will store the
# frequency of the elements of the array.
mp = {i:0 for i in range(len(arr))}
for i in range(n):
# Incrementing the frequency
# of the element by 1.
mp[arr[i]] += 1
for i in range(n):
# Print the element which appear
# less than or equal to k times.
if (mp[arr[i]] <= k):
print(arr[i], end = " ")
# Driver Code
if __name__ == '__main__':
arr = [1, 2, 2, 3, 2, 3, 4]
n = len(arr)
k = 2
RemoveElements(arr, n, k)
# This code is contributed by
# Sahil_Shelangia
C#
// C# program to remove the elements which
// appear more than k times from the array.
using System;
using System.Collections.Generic;
class GFG
{
static void RemoveElements(int [] arr,
int n, int k)
{
// Hash map which will store the
// frequency of the elements of the array.
Dictionary<int,
int> mp = new Dictionary<int,
int>();
for (int i = 0; i < n; ++i)
{
// Incrementing the frequency
// of the element by 1.
if(mp.ContainsKey(arr[i]))
mp[arr[i]]++;
else
mp[arr[i]] = 1;
}
for (int i = 0; i < n; ++i)
{
// Print the element which appear
// less than or equal to k times.
if (mp.ContainsKey(arr[i]) && mp[arr[i]] <= k)
{
Console.Write(arr[i] + " ");
}
}
}
// Driver code
static public void Main()
{
int [] arr = { 1, 2, 2, 3, 2, 3, 4 };
int n = arr.Length;
int k = 2;
RemoveElements(arr, n, k);
}
}
// This code is contributed by Mohit kumar 29
JavaScript
<script>
// JavaScript program to remove the elements which
// appear more than k times from the array.
function RemoveElements(arr,n,k)
{
// Hash map which will store the
// frequency of the elements of the array.
let mp = new Map();
for (let i = 0; i < n; ++i)
{
// Incrementing the frequency
// of the element by 1.
mp.set(arr[i],mp.get(arr[i]) == null?1:mp.get(arr[i])+1);
}
for (let i = 0; i < n; ++i)
{
// Print the element which appear
// less than or equal to k times.
if (mp.has(arr[i]) && mp.get(arr[i]) <= k)
{
document.write(arr[i] + " ");
}
}
}
// Driver code
let arr=[1, 2, 2, 3, 2, 3, 4 ];
let n = arr.length;
let k = 2;
RemoveElements(arr, n, k);
// This code is contributed by unknown2108
</script>
Output:
1 3 3 4
Time Complexity - O(N), where N is the size of the given integer.
Auxiliary Space - O(N), where N is the size of the given integer.
Method #2:Using Built-in Python functions:
- Count the frequencies of every element using Counter function
- Traverse the array.
- Print the elements which appear less than or equal to k times.
Below is the implementation of the above approach:
C++
#include <iostream>
#include <unordered_map>
#include <vector>
void removeElements(const std::vector<int>& arr, int k) {
// Calculating frequencies using unordered_map
std::unordered_map<int, int> freq;
// Counting the frequency of each element
for (int i = 0; i < arr.size(); ++i) {
freq[arr[i]]++;
}
// Print the elements which appear more than or equal to k times
for (int i = 0; i < arr.size(); ++i) {
if (freq[arr[i]] <= k) {
std::cout << arr[i] << " ";
}
}
}
int main() {
std::vector<int> arr = {1, 2, 2, 3, 2, 3, 4};
int k = 2;
removeElements(arr, k);
return 0;
}
Java
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Map;
public class Main {
public static void
removeElements(ArrayList<Integer> arr, int k)
{
// Calculating frequencies using HashMap
Map<Integer, Integer> freq = new HashMap<>();
// Counting the frequency of each element
for (int i = 0; i < arr.size(); ++i) {
freq.put(arr.get(i),
freq.getOrDefault(arr.get(i), 0) + 1);
}
// Print the elements which appear more than or
// equal to k times
for (int i = 0; i < arr.size(); ++i) {
if (freq.get(arr.get(i)) <= k) {
System.out.print(arr.get(i) + " ");
}
}
}
public static void main(String[] args)
{
ArrayList<Integer> arr = new ArrayList<>();
arr.add(1);
arr.add(2);
arr.add(2);
arr.add(3);
arr.add(2);
arr.add(3);
arr.add(4);
int k = 2;
removeElements(arr, k);
}
}
Python3
# Python3 program to remove the elements which
# appear strictly less than k times from the array.
from collections import Counter
def removeElements(arr, n, k):
# Calculating frequencies
# using Counter function
freq = Counter(arr)
for i in range(n):
# Print the element which appear
# more than or equal to k times.
if (freq[arr[i]] <= k):
print(arr[i], end=" ")
# Driver Code
arr = [1, 2, 2, 3, 2, 3, 4]
n = len(arr)
k = 2
removeElements(arr, n, k)
# This code is contributed by vikkycirus
C#
using System;
using System.Collections.Generic;
using System.Linq;
class Program
{
static void RemoveElements(List<int> arr, int k)
{
// Calculating frequencies using Dictionary
Dictionary<int, int> freq = new Dictionary<int, int>();
// Counting the frequency of each element
foreach (int element in arr)
{
if (freq.ContainsKey(element))
{
freq[element]++;
}
else
{
freq[element] = 1;
}
}
// Print the elements which appear more than or equal to k times
foreach (int element in arr)
{
if (freq[element] <= k)
{
Console.Write(element + " ");
}
}
}
static void Main()
{
List<int> arr = new List<int> { 1, 2, 2, 3, 2, 3, 4 };
int k = 2;
RemoveElements(arr, k);
Console.ReadLine();
}
}
JavaScript
function removeElements(arr, k) {
// Calculating frequencies using Map
const freq = new Map();
// Counting the frequency of each element
for (let i = 0; i < arr.length; ++i) {
freq.set(arr[i], (freq.get(arr[i]) || 0) + 1);
}
// Print the elements which appear more than or equal to k times
for (let i = 0; i < arr.length; ++i) {
if (freq.get(arr[i]) <= k) {
console.log(arr[i] + " ");
}
}
}
// Driver code
const arr = [1, 2, 2, 3, 2, 3, 4];
const k = 2;
removeElements(arr, k);
Time Complexity - O(N), where N is the size of the given integer.
Auxiliary Space - O(N), where N is the size of the given integer.
Similar Reads
DSA Tutorial - Learn Data Structures and Algorithms DSA (Data Structures and Algorithms) is the study of organizing data efficiently using data structures like arrays, stacks, and trees, paired with step-by-step procedures (or algorithms) to solve problems effectively. Data structures manage how data is stored and accessed, while algorithms focus on
7 min read
Quick Sort QuickSort is a sorting algorithm based on the Divide and Conquer that picks an element as a pivot and partitions the given array around the picked pivot by placing the pivot in its correct position in the sorted array. It works on the principle of divide and conquer, breaking down the problem into s
12 min read
Merge Sort - Data Structure and Algorithms Tutorials Merge sort is a popular sorting algorithm known for its efficiency and stability. It follows the divide-and-conquer approach. It works by recursively dividing the input array into two halves, recursively sorting the two halves and finally merging them back together to obtain the sorted array. Merge
14 min read
Data Structures Tutorial Data structures are the fundamental building blocks of computer programming. They define how data is organized, stored, and manipulated within a program. Understanding data structures is very important for developing efficient and effective algorithms. What is Data Structure?A data structure is a st
2 min read
Bubble Sort Algorithm Bubble Sort is the simplest sorting algorithm that works by repeatedly swapping the adjacent elements if they are in the wrong order. This algorithm is not suitable for large data sets as its average and worst-case time complexity are quite high.We sort the array using multiple passes. After the fir
8 min read
Breadth First Search or BFS for a Graph Given a undirected graph represented by an adjacency list adj, where each adj[i] represents the list of vertices connected to vertex i. Perform a Breadth First Search (BFS) traversal starting from vertex 0, visiting vertices from left to right according to the adjacency list, and return a list conta
15+ min read
Binary Search Algorithm - Iterative and Recursive Implementation Binary Search Algorithm is a searching algorithm used in a sorted array by repeatedly dividing the search interval in half. The idea of binary search is to use the information that the array is sorted and reduce the time complexity to O(log N). Binary Search AlgorithmConditions to apply Binary Searc
15 min read
Insertion Sort Algorithm Insertion sort is a simple sorting algorithm that works by iteratively inserting each element of an unsorted list into its correct position in a sorted portion of the list. It is like sorting playing cards in your hands. You split the cards into two groups: the sorted cards and the unsorted cards. T
9 min read
Array Data Structure Guide In this article, we introduce array, implementation in different popular languages, its basic operations and commonly seen problems / interview questions. An array stores items (in case of C/C++ and Java Primitive Arrays) or their references (in case of Python, JS, Java Non-Primitive) at contiguous
4 min read
Sorting Algorithms A Sorting Algorithm is used to rearrange a given array or list of elements in an order. For example, a given array [10, 20, 5, 2] becomes [2, 5, 10, 20] after sorting in increasing order and becomes [20, 10, 5, 2] after sorting in decreasing order. There exist different sorting algorithms for differ
3 min read