Find the k largest numbers after deleting the given elements in C++

In this problem, we are given an array arr[] of size n, array del[] of size m, and an integer k. Our task is to find the k largest numbers after deleting the given elements.

We need to print the first k largest elements from the array arr[] found after deleting all elements present in the del[] array. If two instances are present in the array delete the first instance.

Let's take an example to understand the problem,

Input : arr[] = {3, 5, 1, 7, 9, 2}, del[] = {1, 9, 3}, k = 2
Output : 7, 5

Explanation

Array arr[] after deleting the elements : {5, 7, 2}
2 maximum elements are 7, 5.

Solution Approach

A simple solution the problem is by deleting all elements from arr[] that are present in del[]. Then sort the array in descending order and print first k elements of the array.

Example

Program to illustrate the working of our solution

#include 
using namespace std;
void findKmaxElementDelArray(int arr[], int n, int del[], int m, int k){
   for(int i = 0; i ());
   for (int i = 0; i 

Output

2 largest numbers after deleting the elements are 7 5

Another approach

Another approach to solve the problem is using hashmap and heap. We will create a max-heap and a hash map. The hashmap will contain all the elements of the array del[]. And then insert elements of the array arr[] that are not present in hash-map to the max-heap. Pop k elements from the heap and then print it.

Example

Program to illustrate the working of our solution

#include 
using namespace std;
void findKmaxElementDelArray(int arr[], int n, int del[], int m, int k){
   unordered_map deleteElement;
   for (int i = 0; i  maxHeap;
   for (int i = 0; i 

Output

2 largest numbers after deleting the elements are 7 5
Updated on: 2022-01-28T07:46:25+05:30

369 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements