Open In App

Minimum operations to make all Array elements 0 by MEX replacement

Last Updated : 31 Oct, 2023
Improve
Improve
Like Article
Like
Save
Share
Report

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:
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:

  • So we will find out the subarrays which do not contain zero’s.
  • If the subarrays are 0 it means all the elements are 0 so, the answer will be 0.
  • If we found only 1 subarray it means either no 0 is present or 0 is present at only the ends of the array then the operation will be 1.
  • Otherwise, the answer will be 2.

Below is the implementation for the above approach:

C++




// C++ code for the above approach:
#include <bits/stdc++.h>
using namespace std;
int arrayOperations(int N, vector<int>& arr)
{
 
    // Variable to count subarrays
    int subarray = 0;
 
    bool hai = false;
 
    // Loop to count subarrays
    for (int i = 0; i < N; i++) {
 
        // If non zero element occur
        // and hai==true it means
        // previous element was 0
        // so increse the subarrays count
        if (arr[i] != 0) {
            if (!hai)
                subarray++;
            hai = true;
        }
 
        else {
            hai = false;
        }
    }
 
    if (subarray == 0 or subarray == 1)
        return subarray;
 
    return 2;
}
 
// Drivers code
int main()
{
 
    int N = 4;
 
    vector<int> arr = { 3, 0, 4, 5 };
 
    // Function Call
    cout << arrayOperations(N, arr);
 
    return 0;
}


Java




// Java code for the above approach:
 
import java.util.ArrayList;
import java.util.List;
 
public class GFG {
    public static int arrayOperations(int N,
                                      List<Integer> arr)
    {
        // Variable to count subarrays
        int subarray = 0;
 
        boolean hai = false;
 
        // Loop to count subarrays
        for (int i = 0; i < N; i++) {
            // If non-zero element occurs
            // and hai==true it means
            // the previous element was 0
            // so increase the subarrays count
            if (arr.get(i) != 0) {
                if (!hai)
                    subarray++;
                hai = true;
            }
            else {
                hai = false;
            }
        }
 
        if (subarray == 0 || subarray == 1)
            return subarray;
 
        return 2;
    }
 
    // Driver code
    public static void main(String[] args)
    {
        int N = 4;
 
        List<Integer> arr
            = new ArrayList<>(List.of(3, 0, 4, 5));
 
        // Function call
        System.out.println(arrayOperations(N, arr));
    }
}
 
// This code is contributed by rambabuguphka


Python3




# Python code for the above approach:
def arrayOperations(N, arr):
    # Variable to count subarrays
    subarray = 0
    hai = False
 
    # Loop to count subarrays
    for i in range(N):
 
        # If non-zero element occurs
        # and hai is False, it means
        # the previous element was 0
        # so increase the subarrays count
        if arr[i] != 0:
            if not hai:
                subarray += 1
            hai = True
 
        else:
            hai = False
 
    if subarray == 0 or subarray == 1:
        return subarray
 
    return 2
 
 
# Driver code
N = 4
 
# Array with elements 3, 0, 4, 5
arr = [3, 0, 4, 5]
 
# Function call
print(arrayOperations(N, arr))
 
# This code is contributed by Adi


C#




using System;
using System.Collections.Generic;
 
class GFG
{
    static int ArrayOperations(int N, List<int> arr)
    {
        int subarray = 0;
        bool hai = false;
 
        for (int i = 0; i < N; i++)
        {
            if (arr[i] != 0)
            {
                if (!hai)
                    subarray++;
                hai = true;
            }
            else
            {
                hai = false;
            }
        }
 
        if (subarray == 0 || subarray == 1)
            return subarray;
 
        return 2;
    }
 
    static void Main(string[] args)
    {
        int N = 4;
        List<int> arr = new List<int> { 3, 0, 4, 5 };
 
        Console.WriteLine(ArrayOperations(N, arr));
    }
}
// This code is contributed by Aditi Tyagi


Javascript




function arrayOperations(N, arr) {
  let subarray = 0;
  let hai = false;
  // Nikunj Sonigara
  for (let i = 0; i < N; i++) {
    if (arr[i] !== 0) {
      if (!hai) {
        subarray++;
      }
      hai = true;
    } else {
      hai = false;
    }
  }
 
  if (subarray === 0 || subarray === 1) {
    return subarray;
  }
 
  return 2;
}
 
const N = 4;
const arr = [3, 0, 4, 5];
 
// Function Call
console.log(arrayOperations(N, arr));


Output

2





Time Complexity: O(N)
Auxiliary Space: O(1)



Like Article
Suggest improvement
Previous
Next
Share your thoughts in the comments

Similar Reads