C++ Online Compiler
Example: MissingElementsHashing in C++
C
C++
C#
Java
Python
PHP
main.cpp
STDIN
Run
// MissingElementsHashing #include <iostream> #include <vector> #include <unordered_set> // For std::unordered_set using namespace std; // Function to find missing elements using an unordered_set vector<int> findMissingHashing(const vector<int>& arr, int lowerBound, int upperBound) { vector<int> missingElements; if (lowerBound > upperBound) { return {}; // Invalid range } // Step 1: Insert all elements of the input array into an unordered_set unordered_set<int> presentNumbers; for (int num : arr) { // Only insert numbers that could potentially be in the range // This is an optimization; inserting all won't break correctness. if (num >= lowerBound && num <= upperBound) { presentNumbers.insert(num); } } // Step 2: Iterate through the range and check for missing numbers for (int i = lowerBound; i <= upperBound; ++i) { if (presentNumbers.find(i) == presentNumbers.end()) { // If 'i' is not found in the set, it's missing missingElements.push_back(i); } } return missingElements; } int main() { // Step 1: Define the input array and the range vector<int> numbers = {10, 12, 11, 15, 8, 17}; int lower = 10; int upper = 15; cout << "Input array: "; for (int num : numbers) { cout << num << " "; } cout << endl; cout << "Range: [" << lower << ", " << upper << "]" << endl; // Step 2: Call the function to find missing elements vector<int> missing = findMissingHashing(numbers, lower, upper); // Step 3: Display the results cout << "Missing elements in range [" << lower << ", " << upper << "]: "; if (missing.empty()) { cout << "None"; } else { for (int num : missing) { cout << num << " "; } } cout << endl; // Example with a different array vector<int> nums2 = {1, 3, 5, 7, 9}; int lower2 = 1; int upper2 = 10; cout << "\nInput array: "; for (int num : nums2) { cout << num << " "; } cout << endl; cout << "Range: [" << lower2 << ", " << upper2 << "]" << endl; vector<int> missing2 = findMissingHashing(nums2, lower2, upper2); cout << "Missing elements in range [" << lower2 << ", " << upper2 << "]: "; if (missing2.empty()) { cout << "None"; } else { for (int num : missing2) { cout << num << " "; } } cout << endl; return 0; }
Output
Clear
ADVERTISEMENTS