
Data Structure
Networking
RDBMS
Operating System
Java
MS Excel
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
Find the Smallest After Deleting Given Elements Using C++
In this problem, we are given two arrays arr[] and del[]. Our task is to find the smallest after deleting given elements.
We will be deleting values from the array arr[] that are present in del[]. And then print the smallest value after deletion.
Let’s take an example to understand the problem,
Input
arr[] = {2, 5, 6, 9, 1} del[] = {1, 5, 9}
Output
2
Solution Approach
A simple solution to the problem is using hashing. We will insert all the values of del[] array in the hash table. Then we will traverse the array arr[] and check if the values in the hash table. If it is smaller than minVal. If yes, print minVal.
Example
Program to illustrate the working of our solution
#include <bits/stdc++.h> using namespace std; int findSmallestVal(int arr[], int m, int del[], int n){ unordered_map<int, int> delVals; for (int i = 0; i < n; ++i) { delVals[del[i]]++; } int minVal = INT_MAX; for (int i = 0; i < m; ++i) { if (delVals.find(arr[i]) != delVals.end()) { delVals[arr[i]]--; if (delVals[arr[i]] == 0) delVals.erase(arr[i]); } else minVal = min(minVal, arr[i]); } return minVal; } int main(){ int array[] = { 5, 12, 33, 4, 56, 12, 20 }; int m = sizeof(array) / sizeof(array[0]); int del[] = { 12, 4, 56, 5 }; int n = sizeof(del) / sizeof(del[0]); cout<<"The smallest value after the deleting element is "<<findSmallestVal(array, m, del, n); return 0; }
Output
The smallest value after the deleting element is 12
Advertisements