![]() |
VOOZH | about |
Given an array of N integers. You can perform an operation that selects a contiguous subarray and replaces all its elements with the MEX (smallest non-negative integer that does not appear in that subarray), the task is to find the minimum number of operations required to make all the elements of the array 0.
Examples:
Input: N = 4, arr = {3, 0, 4, 5}
Output: 2
Explanation: First, you have to choose l = 0, r = 0, and in the second operation, you have to choose l = 2, r = 3.Input: N = 4, arr = {0, 0, 0, 0}
Output: 0
Explanation: All the elements are already 0.
Approach: To solve the problem follow the below observations:
We can do the question by just some observation, and the observation is given below:
- Think if there is not any 0 present then the MEX of the complete array will be 0. So we can choose the complete array and make it as 0 in just one operation.
- If all elements are 0 then no need to do any operation.
- Now if 0 is present at only corners then what we can do, we can choose all the elements leaving the corner 0 and the MEX of them will be 0 and make them 0 in one operation.
- Now the last case occur when there can by 0's random in the array. So in that can what we can do we can select the complete array and MEX of the complete array will be some non-zero number as 0 is present in the array. So we will change whole array to that MEX in one operation and after that we will again select the complete array and now the MEX will be 0. So we will replace every element with 0 in second operation.
Follow the steps to solve the problem:
Below is the implementation for the above approach:
2
Time Complexity: O(N)
Auxiliary Space: O(1)