Minimum Increments To Reach The Given Mex In C++ - C++ Programming Tutorial
C++ Course / Miscellaneous / Minimum Increments To Reach The Given Mex In C++

Minimum Increments To Reach The Given Mex In C++

BLUF: Mastering Minimum Increments To Reach The Given Mex In C++ is a critical step in becoming a proficient C++ developer. This lesson provides a deep dive into the syntax, performance considerations, and real-world applications of this concept.
Key Performance Insight: Minimum Increments To Reach The Given Mex In C++

C++ is renowned for its efficiency. Learn how Minimum Increments To Reach The Given Mex In C++ enables low-level control and high-performance computing in the tutorial below.

In C++, there is a scenario where the goal is to determine the Minimum Excluded (MEX) value in an array with the least number of increments. The MEX value essentially identifies the smallest non-negative integer that is absent in the array elements. The end result of this operation is an array that is filled with the minimum increments needed to accommodate all non-negative integers up to the specified MEX value.

This process involves performing sorting and binary search procedures. Initially, you arrange the elements in the array in a sorted manner. Subsequently, you employ binary search to determine the location of the MEX within the sorted array. The disparity between the identified MEX and their positions provides the minimal count of steps required. This technique showcases the construction of the array while ensuring that the MEX condition is optimized with a time complexity of O(N).

MEX (Minimum EXcluded):

MEX refers to the Minimum EXcluded value, which is the smallest non-negative integer not found within the given array.

The issue lies in the fact that the increment operation will maintain the array that holds integers within the range from 0 to the specified MEX value.

Minimum Increments:

An "increment" is defined in this context as raising the value of an array element by 1.

The goal is to determine the smallest amount of increments required to achieve the desired Minimum Excludant (MEX).

Approach 1: Using Sorting

Example

#include <iostream>
#include <vector>
#include <algorithm>
using namespace std;
//Function to calculate the minimum increments to reach the given MEX
int minIncrementsToMex(const vector<int>& nums, int mex) {
    // Step 1: Sort the array
    vector<int> sorted_nums = nums;
    sort(sorted_nums.begin(), sorted_nums.end());
    // Step 2: Initialize variables for tracking increments and current MEX
    int increments = 0;
    int current_mex = 0;  // Initialize current MEX
    // Step 3: Iterate through the sorted array
    for (int i = 0; i < sorted_nums.size(); ++i) {
        // Step 3a: Check if the element is equal to the current MEX
        if (sorted_nums[i] == current_mex) {
            // If yes, move to the next MEX
            current_mex++;
        } else if (sorted_nums[i] > current_mex) {
            // Step 3b: If the element is greater than the current MEX,
            // increment the current MEX and add the difference to increments
            current_mex++;
            increments += (current_mex - sorted_nums[i]);
        }
        // If the element is less than the current MEX, it's already processed
        // and doesn't require an increment.
    }
    // Step 4: Handle remaining MEX values after the sorted array ends
    increments += (mex - current_mex);
    // Step 5: Return the total increments
    return increments;
}
int main() {
    // Example usage
    vector<int> nums = {1, 3, 2, 5};
    int mex = 4;
    // Step 6: Call the Function to get the result
    int result = minIncrementsToMex(nums, mex);
    // Step 7: Output the result
    cout << "Original Array: ";
    for (int num : nums) {
        cout << num << " ";
    }
    cout << endl;
    cout << "Minimum increments required to reach MEX " << mex << ": " << result << endl;
    // Step 8: Return from main Function
    return 0;
}

Output:

Output

Original Array: 1 3 2 5 
Minimum increments required to reach MEX 4: 0

Explanation:

The provided C++ code addresses the challenge of calculating the minimum number of increments needed to achieve a specified MEX (Minimum Excluded) value within a provided list. This is accomplished by arranging the array in ascending order and identifying the minimum value at each step.

  • Arranging the array:

The values from the initial array (nums) are initially duplicated into a fresh vector (sorted_nums), which is subsequently organized using the sort function to arrange it in ascending order. The sorting process is a crucial step in traversing through the array elements.

  • Monitoring Variables:

Two variables are employed to monitor the advancement across the array and the changes applied:

Increments: When initialized to 0, this variable keeps track of the total count of increments performed.

The present_mex variable signifies the ongoing MEX value for the array element during each iteration, commencing from an initial value of zero.

When traversing the sorted array:

The loop goes over the arranged array (sorted_nums). In each iteration, the code examines the connection between the current element and the current Minimum EXcludant (MEX):

So when the element matches the current minimum excluded value (MEX), it indicates that the MEX has been identified, and the script increases the current_me[x] to progress to the subsequent MEX.

Suppose the element surpasses the existing MEX value; the program will then increase the current MEX by one, and the total count will increase by the absolute variance between the MEX and the element. Consequently, the array becomes populated with sequential integers, albeit at the cost of efficiency.

  • Dealing with Remaining MEX Values:

After arranging the array in a sorted order, the subsequent action involves examining the Minimum Excludant (MEX) in relation to the succeeding values and populating them accordingly. Consequently, the last processed MEX value is subtracted from the designated MEX value. The resulting variance is subsequently integrated into the cumulative increments.

Return Result:

The function will output the overall number of compliments needed to achieve the specified MEX value, representing the minimum amount of compliments necessary.

Example Usage in Main:

The primary Function showcases how the algorithm operates by taking into account a provided array (nums) and a specified MEX value. It calls the minIncrementsToMex Function with these parameters and then outputs the outcome.

The software showcases the initial array and the minimal increments necessary to reach the desired MEX value. This aids individuals in comprehending how adjustments to the array align with the MEX criteria.

Complexity Analysis:

The time and spatial efficiency of the provided C++ code can be analyzed to identify the smallest adjustment required to reach the target MEX value, thus assessing its efficacy.

Time Complexity:

The time complexity is influenced by the method of arranging the data. Within the C++ Standard Template Library (STL), the sort function typically achieves an average time complexity of O(n log n), with 'n' denoting the size of the input array.

Sorting the Array:

The sorting process arranges the array sorted_nums, which has a size of 'n'. The time complexity of this sorting algorithm is O(n log n).

The algorithm examines the array sequentially following the sorting process. Each cycle involves operations that take constant time, such as comparisons and increments. Consequently, the overall time complexity for this stage amounts to O(n).

Handling Remaining MEX Values:

The final stage, which involves processing the remaining MEX values, similarly consists of operations that take constant time, thereby contributing O(1) to the total time complexity.

The overall time complexity hinges on the primary factor, which is the sorting algorithm. Therefore, the complete time complexity of the script amounts to O(n log n).

Space ComplexityAnalysis:

The space efficiency of the code is impacted by the dynamic creation and utilization of data structures throughout the algorithm's runtime.

Sorted Array (sorted_nums):

A new vector named sorted_nums is generated to hold the sorted array elements. The space complexity of this vector is O(n), with 'n' representing the length of the initial array.

Tracking Variables (increments and current_mex):

Two integer variables (increments and current_mex) are employed to monitor the increments and the present MEX value. These variables possess fixed space demands and add O(1) to the space complexity.

Other Local Variables:

The code makes use of additional local variables like loop counters and temporary variables, which occupy a fixed amount of space and add a constant factor to the total space complexity of O(1).

The primary factor impacting space complexity is the amount of memory needed for the ordered array. Consequently, the total space complexity of the program is O(n).

Approach 2: Using Counting Array

Example

#include <iostream>
#include <vector>
using namespace std;
//Function to calculate the minimum increments to reach the given MEX using a counting array
int minIncrementsToMex(const vector<int>& nums, int mex) {
    // Check for invalid input conditions
    if (mex < 0) {
        // Return -1 for invalid MEX
        return -1;
    }
    // Step 1: Create a Counting Array
    // The counting array will keep track of the occurrences of each integer
    // The size of the counting array is determined by the specified MEX value
    vector<int> count(mex + 1, 0);
    // Step 2: Count Occurrences in Original Array
    // Iterate through the original array and update the counting array
    // with the occurrences of each integer (up to the specified MEX)
    for (int num : nums) {
        if (num <= mex) {
            count[num]++;
        }
    }
    // Step 3: Iterate Through Counting Array
    // Initialize variables for tracking increments and the current MEX
    int current_mex = 0;
    int increments = 0;
    // Iterate through the counting array to identify gaps and make increments
    for (int i = 0; i <= mex; ++i) {
        // Check if the current index represents a gap
        // If count[i] is greater than 0, it means the integer i is present in the array
        // If i is greater than the current MEX, make increments to fill the gap
        while (count[i] > 0 && i > current_mex) {
            current_mex++;
            increments += (current_mex - i);
        }
    }
    // Return the total increments
    return increments;
}
int main() {
    // Example usage
    vector<int> nums = {1, 3, 2, 5};
    int mex = 4;
    // Call the Function to get the result
    int result = minIncrementsToMex(nums, mex);
    //Output the result
    cout << "Original Array: ";
    for (int num : nums) {
        cout << num << " ";
    }
    cout << endl;
    // Display the result
    cout << "Minimum increments required to reach MEX " << mex << ": " << result << endl;
    // Return from main Function
    return 0;
}

Output:

Output

Original Array: 1 3 2 5 
Minimum increments required to reach MEX 4: 0

Explanation:

The provided C++ code is designed to determine the minimum number of additions needed to achieve a specific MEX element in an array using a counting array technique.

  • Setting up the Counting Array (count):

Initially, a frequency array (count) will be initialized with a length of MEX + 1, where MEX denotes the maximum element. This array keeps track of the frequency of each number within the range of 0 to the MEX.

  • Determining Frequencies in the Initial Array (nums):

Iterating Over the Counting Array:

Traversing the counting array allows us to access and process the occurrence count of each integer up to its corresponding MEX value.

Two variables are set up initially: the variable current_mex holds the MEX value and increments counts the total number of increments performed. As a result, the algorithm loops through the counting array. At each index, it checks for any gap between the current MEX value and the index. If a gap indicates missing integers, a series of increments is executed to populate those gaps. Each increment is adjusted by the difference between the current MEX and the index.

  • Returning the Total Number of Increments:

The function provides the cumulative increment total and the minimum number of increments needed to reach the Minimum Excludant (MEX) initially.

Error Management:

  • Handling Incorrect Input:

The code includes validation for inappropriate inputs. If the specified MEX value is negative, the function will return -1, indicating that the MEX value is not valid.

  • Demonstration of Usage in Main:

The primary scenario demonstrates the process of executing the algorithm on an array named "nums" while specifying a MEX value. The function is invoked using these specific parameters, leading to the desired outcome which is then displayed through printing.

Output Display:

The software showcases the original array and the minimum count of increase operations necessary to achieve the desired MEX value. In cases where the MEX cannot be obtained or the input is invalid, an appropriate message will be displayed.

Complexity Analysis:

We have the ability to determine the running time and amount of memory used by the provided C++ code in order to assess its efficiency.

Time Complexity Analysis:

The primary element influencing the algorithmic complexity is the loops over the original array (nums) and the subsequent loops over the counting array.

Counting Occurrences in the Original Array:

The most nested loop will cycle through the initial array (nums), with a time complexity of O(n), where 'n' represents the length of the array.

Iterating Through the Counting Array:

In the second iteration, the loop variable iterates over the counting array, which has a length of MEX + 1. If we consider the worst-case scenario, the loop will run for 'MEX' iterations. Consequently, the time complexity of this loop is O(MEX).

By combining two actions, the time complexity of the code becomes O(n + MEX). When 'MEX' is significantly less than 'n', the term 'n' takes precedence, resulting in a simplified time complexity of O(n).

Space Complexity Analysis:

The additional data structures formed determine the amount of space or extra memory that the algorithm necessitates.

Counting Array (count):

The storage space required by the counting array (count) amounts to O(MEX + 1), directly linked to the particular MEX value. As a result, the spatial complexity is O(mex).

Tracking Variables (current_mex and increments):

Two integer variables (designated as current_mex and increments) are employed in this context to monitor the advancement of the array and the increments applied. These variables occupy a fixed amount of memory, contributing to the overall space complexity of O(1).

Other Local Variables:

The code also employs additional local variables such as loop counters and temporary variables, which consume O(1) constant space and impact the total space complexity.

Approach 3: Using HashSet

Example

A HashSet is a data structure that allows for constant-time average case complexity for basic operations such as insertion, deletion, and lookup.
#include <iostream>
#include <vector>
#include <unordered_set>
using namespace std;
//Function to calculate the minimum increments to reach the given MEX using a HashSet
int minIncrementsToMex(const vector<int>& nums, int mex) {
    // Step 1: HashSet Initialization
    unordered_set<int> seen;
    // Step 2: Count Occurrences in Original Array
    for (int num : nums) {
        seen.insert(num);
    }
    // Step 3: Iterate to Find the MEX
    while (seen.count(mex)) {
        mex++;
    }
    // Step 4: Return Total Increments
    return mex - seen.size();
}
int main() {
    // Example usage
    vector<int> nums = {1, 3, 2, 5};
    // Input the desired MEX value
    int desiredMex;
    cout << "Enter the desired MEX value: ";
    cin >> desiredMex;
    // Call the Function to get the result
    int result = minIncrementsToMex(nums, desiredMex);
    //Output the result
    cout << "Original Array: ";
    for (int num : nums) {
        cout << num << " ";
    }
    cout << endl;
    // Display the result
    cout << "Minimum increments required to reach MEX " << desiredMex << ": " << result << endl;
    // Return from main Function
    return 0;
}

Output:

Output

Enter the desired MEX value: 4
Original Array: 1 3 2 5 
Minimum increments required to reach MEX 4: 0

Explanation:

Utilizing a HashSet data structure, the provided C++ code determines the minimum number of increments necessary to reach the desired MEX (Minimum Excluded) value within an array. This approach efficiently monitors unique elements within the array and identifies the smallest non-negative integer that is absent.

  • HashSet Setup:

The process begins with the initialization of a HashSet named "seen" using the unordered_set container from the C++ STL. This particular HashSet is tasked with storing distinct elements found within the array.

  • Determine the Frequency of Elements in the Original Array:

A loop is used to traverse through the original array (nums array), appending each element to the 'seen' dictionary. This ensures that the 'seen' dictionary will contain only distinct elements from the original array, simplifying the process of determining the existing integers in the array and those that are absent.

  • Perform Iteration to Discover the MEX:

After determining the frequency of each element in the initial array, a variable called 'mex' is set to 0. The goal is to identify the Minimum EXcluded value, which is the smallest non-negative integer that is absent from the array. To verify if the current 'mex' value exists in the HashSet, a while loop is employed. If it is discovered, the 'mex' value is incremented until a value that is not present in the array is found.

  • Provide the Total Count of Incrementations:

When the loop identifies the MEX value, the function provides the total number of reductions required to achieve that MEX. This is calculated by subtracting the final 'mex' value from the size of the 'seen' HashSet, which indicates the count of distinct elements in the original array.

  • User Input for the Target MEX Value:

The primary function prompts the user to provide the ME value. The variable 'desiredMex' is then set to the inputted value. Consequently, the function minIncrementsToMex is invoked post adjustment with the input (nums) and the user's MEX value.

  • Display of Output:

The software generates the initial array and calculates the minimum modifications required to define the MEX. It utilizes a loop to showcase each item in the original array. The result is presented to the user indicating the minimal increments necessary to achieve the desired MEX value.

Complexity Analysis:

The efficiency of the given C++ code can be assessed by examining its time and space complexity, which indicates how well it utilizes resources during runtime.

Time Complexity Analysis:

The computational efficiency of the code is determined by analyzing the operations within the loop that cycles through the initial array, modifies the HashSet, and searches for the Minimum Excluded Value (MEX).

Initializing a HashSet and Counting Instances: Establishing an unordered_set and looping through the initial array incurs a time complexity of O(n). This is due to the necessity of processing each element within the array at least once.

Finding the Minimum Excludant (MEX): The execution time of the while loop responsible for iteratively determining the MEX is directly influenced by the specific MEX value. If the MEX surpasses the size of the array, the algorithm's time complexity becomes O(mex), where 'mex' denotes the desired MEX value.

Overall, the time complexity of the algorithm is primarily determined by the O(n) factor, resulting in a worst-case scenario time complexity of O(n + mex).

Space Complexity Analysis:

The space efficiency of the program is influenced by the extra data structures generated at runtime.

HashSet (seen): The HashSet named 'seen' is employed to maintain a record of unique items encountered in the initial array. In the scenario where all elements are different, the HashSet's size could reach 'n', which is the size of the input array. As a result, the space complexity associated with a HashSet is O(n).

Variables (mex): The memory consumption for data types such as 'mex' remains fixed, which results in an O(1) contribution to the overall space complexity.

The amount of space allocated for user input remains consistent and is not influenced by the size of the input array.

By computing these factors, the program's time complexity is determined to be O(n).

Approach 4: Using Binary Search Algorithm

Another approach involves utilizing binary search, which is another technique that can be applied to determine the MEX in an ordered array. This strategy involves conducting a binary search to validate the initial estimate, arranging the array, and subsequently identifying the smallest absent non-negative integer.

Example

#include <iostream>
#include <vector>
#include <algorithm>
using namespace std;
//Function to calculate the minimum increments to reach the given MEX using Binary Search
int minIncrementsToMex(const vector<int>& nums) {
    // Step 1: Sort the array
    vector<int> sortedNums(nums.begin(), nums.end());
    sort(sortedNums.begin(), sortedNums.end());
    // Step 2: Binary Search for MEX
    int low = 0, high = sortedNums.size();
    while (low < high) {
        int mid = low + (high - low) / 2;
        if (sortedNums[mid] > mid) {
            // Missing element is on the left side
            high = mid;
        } else {
            // Missing element is on the right side
            low = mid + 1;
        }
    }
    // 'low' now represents the position of the MEX
    // Step 3: Calculate Increments
    int mex = low;
    int increments = mex;
    return increments;
}
int main() {
    // Example usage
    vector<int> nums = {1, 3, 2, 5};
    // Call the Function to get the result
    int result = minIncrementsToMex(nums);
    //Output the result
    cout << "Original Array: ";
    for (int num : nums) {
        cout << num << " ";
    }
    cout << endl;
    //Output the sorted array
    cout << "Sorted Array: ";
    for (int num : nums) {
        cout << num << " ";
    }
    cout << endl;
    // Display the result
    cout << "Minimum increments required to reach MEX: " << result << endl;
    // Return from the main Function
    return 0;
}

Output:

Output

Original Array: 1 3 2 5 
Sorted Array: 1 3 2 5 
Minimum increments required to reach MEX: 0

Explanation:

Employing a binary search approach, the C++ code provided is designed to determine the minimum number of increments needed to achieve the specified Minimum Excluded (MEX) value within the provided array.

Function minIncrementsToMex:

Arrange the Array in Ascending Order:

Firstly, the Function duplicates the initial array and proceeds to arrange it in ascending order by utilizing the sort function within the C++ STL.

  • Implementing Binary Search for MEX:

It proceeds by establishing 'low' and 'high' pointers to define the search scope within the array. The function proceeds with a binary search operation until the 'low' pointer exceeds or equals the 'high' pointer. Throughout each cycle, it computes the middle index and evaluates the values at that position against the index. Using this evaluation, it refines the search area towards the left or right side, as dictated by the outcomes.

  • Determine Increment Values:

Upon completion of the binary search algorithm, the function determines the Minimum Excludant (MEX) value and computes the minimum increment required to reach it. The variable 'mex' holds the determined MEX value, while the 'increments' variable stores the calculated result.

  • Main Function:

The showcase feature illustrates how the minIncrementsToMex function is applied using a sample array. The demonstration includes displaying both the initial and sorted arrays, along with the minimum number of steps necessary to achieve the desired MEX value.

Code Execution:

Sort Original Array: The initial array, consisting of numbers 1, 3, 2, and 5, has been sorted and the sorted array is displayed.

Binary Search and Increment Calculation: Binary search is utilized to find the index of the minimum excluded value (MEX) in a sorted array, allowing for the determination of both the MEX value and the subsequent increments.

Output Display: Finally, the initial arrays and the sorted arrays, along with the minimum increments, are displayed as the ultimate outcome.

Complexity Analysis:

Time Complexity Analysis:

Sorting the Array:

The code arranges the input array by utilizing the sort function provided by the C++ STL library. Typically, the time complexity of the sorting process is O(n log n), where 'n' represents the size of the array.

Binary Search for MEX:

The sorted array undergoes the binary search algorithm to determine the MEX value. By halving the search space in each iteration, this algorithm operates in O(log n) time complexity, with n representing the sorted array's size. This systematic approach ensures efficient location of the target value within the array.

Ultimately, arranging elements in a specific order plays a crucial role in determining the time complexity. Consequently, the time complexity of the algorithm is O(n log n).

Space Complexity Analysis:

Sorted Array (sortedNums):

A fresh vector named sortedNums is created to store the ordered form of the provided array. The space complexity associated with this process is influenced by the selection of the sorting algorithm. In scenarios where an in-place sorting technique is utilized, the space complexity is O(1) as it arranges the array within the existing memory allocation. Furthermore, the supplementary memory required for sorting may reach O(n) in the most unfavorable instances.

Variables (low, high, mid, mex, increments):

These variables have a fixed size and contribute O(1) to the overall space complexity.

Input Array (nums):

The original array remains intact, without any additional space being utilized.

Taking these aspects into account, the maximum space complexity of the code is O(n) when additional memory is employed for sorting. Conversely, the space complexity could decrease to O(1) in case an in-place sorting algorithm is employed.

Input Required

This code uses input(). Please provide values below:

Logic Practice
Install Logic Practice
Add to home screen for a faster app-like experience