Final MEX to Zero

You are given an array nums of length n, where n >= 4 and each element is a non-negative integer.

In one operation, choose any subarray nums[l...r] with length at least 2 and replace it with a single integer equal to its MEX, where MEX is the smallest non-negative integer missing from that subarray.

Keep performing operations until only one element remains. Your task is to find any sequence of operations such that the final remaining element is 0.

It is guaranteed that at least one valid sequence always exists, and you do not need to minimize the number of operations.

Note: This problem can have multiple valid sequences of operations. Since the exact output may differ from one correct solution to another, the checker prints true if the produced sequence is valid and false otherwise, instead of matching one fixed output.

MEX Definition:

The MEX of a collection of integers is the smallest non-negative integer that does not appear in it.

Examples:

  • mex([1, 2, 4]) = 0
  • mex([0, 1, 3]) = 2
  • mex([0, 1, 2]) = 3

Example 1:

Input: nums = [1, 2, 3, 4]

Output: [[1, 4]]

Explanation:

The whole array does not contain 0, so its MEX is 0. Replacing the entire array gives [0].

Example 2:

Input: nums = [0, 1, 2, 3]

Output: [[1, 2], [1, 3]]

Explanation:

First replace [0, 1] with 2, so the array becomes [2, 2, 3].

Then replace [2, 2, 3] with 0, so the array becomes [0].

Now Your Turn!

Pick the correct output for the given input

Input: nums = [1, 0, 2, 4]

Still unsure what the problem is asking ?

Let’s go through a few more examples, step by step, to make it clearer.

Constraints:

  • 4 <= n <= 5000
  • 0 <= nums[i] <= n

Hints

Frequently Occurring Doubts

Interview Follow-up Questions

0
class Solution {
public:
vector<vector<int>> finalMexToZero(vector<int>& a) {
// Your code goes here
}
};
Test Case

Input:

Nums