C++ Online Compiler
Example: MissingElementsBooleanArray in C++
C
C++
C#
Java
Python
PHP
main.cpp
STDIN
Run
// MissingElementsBooleanArray #include <iostream> #include <vector> #include <numeric> // For std::iota if needed, though not strictly for this problem #include <algorithm> // For std::max_element, std::min_element using namespace std; // Function to find missing elements using a boolean array vector<int> findMissingBooleanArray(const vector<int>& arr, int lowerBound, int upperBound) { if (lowerBound > upperBound) { return {}; // Invalid range } // Determine the size needed for the boolean array // We need indices from lowerBound to upperBound // So, size = (upperBound - lowerBound + 1) vector<bool> present(upperBound - lowerBound + 1, false); // Mark numbers present in the input array for (int num : arr) { // Only consider numbers within the specified range if (num >= lowerBound && num <= upperBound) { present[num - lowerBound] = true; } } // Collect missing numbers vector<int> missingElements; for (int i = 0; i <= upperBound - lowerBound; ++i) { if (!present[i]) { missingElements.push_back(i + lowerBound); } } 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 = findMissingBooleanArray(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 range or array vector<int> nums2 = {1, 3, 5}; int lower2 = 1; int upper2 = 5; cout << "\nInput array: "; for (int num : nums2) { cout << num << " "; } cout << endl; cout << "Range: [" << lower2 << ", " << upper2 << "]" << endl; vector<int> missing2 = findMissingBooleanArray(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