Open In App
Related Articles

Minimum length of subarray in given Ternary Array having 0 as the majority element

Improve
Improve
Improve
Like Article
Like
Save Article
Save
Report issue
Report

Given an integer array arr[] of size n with only three types of integers 0’s, 1’s, and 2’s. Find the minimum length of the subarray of the array arr[] of length >=2, such that it has a frequency of 0’s greater than both 1’s and 2’s. If not found print -1

Input: arr[] = {2, 0, 2, 0, 1, 2, 2, 2}
Output : 3
Explanation: {0, 2, 0} from index [2, 4] is the subarray with frequencies of 0’s greater frequencies of 1’s and 2’s.

Input: arr[] = {2, 2, 2, 2}
Output: -1 

 

Naive Approach: This problem can be done by going through every subarray and checking the frequencies of 0’s, 1’s and 2’s and checking if the frequency of 0’s is greater than both 2’s and 1’s then storing the minimum length of subarray as the answer.

  • Iterate over the given array arr[]
    • Find the number of zeros, one’s and two’s in the current subarray
    • Check if the current subarray size is greater than equals to 2 and the number of zeros is greater than the number of ones and two’s then, update the min_len
    • Check if a valid subarray exists.
      •  if not, return -1
  • Return min_len;

Below is the implementation of the above approach:

C++

// C++ code for the above approach
#include <bits/stdc++.h>
using namespace std;
 
// Function to find the minimum
// subarray length with most 0's
int minLength(vector<int> arr)
{
    int min_len = INT_MAX;
    int n = arr.size();
 
    // Iterate over the given array arr[]
    for (int i = 0; i < n; i++) {
        int zeroCount = 0;
        int oneCount = 0;
        int twoCount = 0;
 
        // Find the number of zero, one and two in the
        // current subarray
        for (int j = i; j < n; j++) {
            if (arr[j] == 0)
                zeroCount++;
            else if (arr[j] == 1)
                oneCount++;
            else if (arr[j] == 2)
                twoCount++;
 
            int currSubarrayLength = (j - i + 1);
 
            // Check if the current subarray size is greater
            // than equals to 2 and number of zero is
            // greater that number of one's and two's then,
            // update the min_len
            if (currSubarrayLength >= 2
                && zeroCount > oneCount
                && zeroCount > twoCount) {
                min_len = min(min_len, (j - i + 1));
            }
        }
    }
 
    // Check if valid subarray exist.
    // if not, return -1
    if (min_len == INT_MAX)
        return -1;
 
    // Return min_len;
    return min_len;
}
 
// Driver Code
int main()
{
 
    // Initializing list of nums
    vector<int> arr = { 2, 0, 2, 0, 1, 2, 2, 2 };
 
    // Call the function and print the answer
    cout << (minLength(arr));
 
    return 0;
}

                    

Java

import java.util.Arrays;
import java.util.List;
 
public class Gfg {
    // Function to find the minimum
    // subarray length with most 0's
    static int minLength(List<Integer> arr)
    {
        int minLen = Integer.MAX_VALUE;
        int n = arr.size();
 
        // Iterate over the given array arr[]
        for (int i = 0; i < n; i++) {
            int zeroCount = 0;
            int oneCount = 0;
            int twoCount = 0;
 
            // Find the number of zero, one and two in the
            // current subarray
            for (int j = i; j < n; j++) {
                if (arr.get(j) == 0)
                    zeroCount++;
                else if (arr.get(j) == 1)
                    oneCount++;
                else if (arr.get(j) == 2)
                    twoCount++;
 
                int currSubarrayLength = (j - i + 1);
 
                // Check if the current subarray size is
                // greater than equals to 2 and number of
                // zero is greater that number of one's and
                // two's then, update the min_len
                if (currSubarrayLength >= 2
                    && zeroCount > oneCount
                    && zeroCount > twoCount) {
                    minLen = Math.min(minLen, (j - i + 1));
                }
            }
        }
 
        // Check if valid subarray exist.
        // if not, return -1
        if (minLen == Integer.MAX_VALUE)
            return -1;
 
        // Return minLen;
        return minLen;
    }
 
    public static void main(String[] args)
    {
        // Initializing list of nums
        List<Integer> arr
            = Arrays.asList(2, 0, 2, 0, 1, 2, 2, 2);
 
        // Call the function and print the answer
        System.out.println(minLength(arr));
    }
}

                    

Python3

# Python code implementation for the above approach
 
# Function to find the minimum
# subarray length with most 0's
def minLength(arr):
    minLen = float('inf')
    n = len(arr)
     
    # Iterate over the given array arr[]
    for i in range(n):
        zeroCount = 0
        oneCount = 0
        twoCount = 0
 
        # Find the number of zero, one
        # and two in the current subarray
        for j in range(i, n):
            if arr[j] == 0:
                zeroCount += 1
            elif arr[j] == 1:
                oneCount += 1
            elif arr[j] == 2:
                twoCount += 1
 
            currSubarrayLength = (j - i + 1)
 
            # Check if the current subarray size is
            # greater than equals to 2 and number of
            # zero is greater that number of one's and
            # two's then, update the min_len
            if currSubarrayLength >= 2 and zeroCount > oneCount and zeroCount > twoCount:
                minLen = min(minLen, (j - i + 1))
 
    # Check if valid subarray exist.
    # if not, return -1
    if minLen == float('inf'):
        return -1
 
    # Return minLen
    return minLen
   
# Initializing list of nums
arr = [2, 0, 2, 0, 1, 2, 2, 2]
# Call the function and print the answer
print(minLength(arr))
 
# This code is contributed by lokeshmvs21.

                    

Javascript

// Function to find the minimum subarray length with most 0's
function minLength(arr) {
    let min_len = Number.MAX_SAFE_INTEGER;
    let n = arr.length;
     
    // Iterate over the given array arr[]
    for (let i = 0; i < n; i++) {
    let zeroCount = 0;
    let oneCount = 0;
    let twoCount = 0;
     
     
    // Find the number of zero, one and two in the current subarray
    for (let j = i; j < n; j++) {
      if (arr[j] === 0) {
        zeroCount++;
      } else if (arr[j] === 1) {
        oneCount++;
      } else if (arr[j] === 2) {
        twoCount++;
      }
     
      let currSubarrayLength = j - i + 1;
     
      // Check if the current subarray size is greater than equals to 2
      // and number of zero is greater than number of one's and two's
      // then, update the min_len
      if (
        currSubarrayLength >= 2 &&
        zeroCount > oneCount &&
        zeroCount > twoCount
      ) {
        min_len = Math.min(min_len, j - i + 1);
      }
    }
}
 
// Check if valid subarray exist. If not, return -1
if (min_len === Number.MAX_SAFE_INTEGER) {
return -1;
}
 
// Return min_len;
return min_len;
}
 
// Driver Code
let arr = [2, 0, 2, 0, 1, 2, 2, 2];
 
// Call the function and print the answer
console.log(minLength(arr));

                    

C#

using System;
using System.Linq;
using System.Collections.Generic;
 
class Gfg {
    // Function to find the minimum
    // subarray length with most 0's
    static int minLength(List<int> arr)
    {
        int minLen = int.MaxValue;
        int n = arr.Count;
 
        // Iterate over the given array arr[]
        for (int i = 0; i < n; i++) {
            int zeroCount = 0;
            int oneCount = 0;
            int twoCount = 0;
 
            // Find the number of zero, one and two in the
            // current subarray
            for (int j = i; j < n; j++) {
                if (arr[j] == 0)
                    zeroCount++;
                else if (arr[j] == 1)
                    oneCount++;
                else if (arr[j] == 2)
                    twoCount++;
 
                int currSubarrayLength = (j - i + 1);
 
                // Check if the current subarray size is
                // greater than equals to 2 and number of
                // zero is greater that number of one's and
                // two's then, update the min_len
                if (currSubarrayLength >= 2
                    && zeroCount > oneCount
                    && zeroCount > twoCount) {
                    minLen = Math.Min(minLen, (j - i + 1));
                }
            }
        }
 
        // Check if valid subarray exist.
        // if not, return -1
        if (minLen == int.MaxValue)
            return -1;
 
        // Return minLen;
        return minLen;
    }
 
    public static void Main(string[] args)
    {
        // Initializing list of nums
        List<int> arr
            = new List<int>{ 2, 0, 2, 0, 1, 2, 2, 2 };
 
        // Call the function and print the answer
        Console.WriteLine(minLength(arr));
    }
}

                    

Output
3

Time Complexity: O(n*n)
Auxiliary Space: O(1)

Efficient Approach: Since there are only 3 types of integers the possible subarrays of length >=2 satisfying the above condition would be 

{0, 0}, {0, 1, 0}, {0, 2, 0}, {0, 1, 2, 0}, {0, 2, 1, 0}, {0, 0, 0, 1, 1, 2, 2}, ….

The maximum possible minimum length of subarray would be 7. Any other subarray which satisfies the above condition with length > 7 would contain any of the above subarrays in it so the maximum possible length of subarray which satisfies the above condition is 7.

 Follow these steps to solve this problem:

  • Initialize a variable min_length as INT_MAX
  • Iterate in the range [0, n) using the variable i and perform the following tasks:
    • Initialize an array count[] with initial frequencies 0
    • Increment the frequency of arr[i] using count[arr[i]]++.
    • Iterate in the range [i+1, min(n, i+7)) using the variable j and perform the following tasks:
      • Increment the frequency of arr[j] by using count[arr[j]]++ of each subarray of size <=7.
      • If the count[0] is greater than both count[1] and count[2] and if min_length > j-i+1 then assign min_length = j-i+1
  • If min_length is equal to INT_MAX return -1.
  • Else print min_length as the answer.

Below is the implementation of the above approach.

C++

// C++ code for the above approach
#include <bits/stdc++.h>
using namespace std;
 
// Function to find the minimum
// subarray length with most 0's
int minLength(vector<int> arr)
{
    int min_len = INT_MAX;
    int n = arr.size();
 
    // Traverse the array to check
    // the required condition
    for (int i = 0; i < n; i++) {
 
        // Initialize a vector count
        // to store the frequencies
        int count[3] = { 0 };
        count[arr[i]]++;
 
        // Check all subarrays of length
        // <=7 and count the frequencies
        for (int j = i + 1; j < min(n, i + 7); j++) {
            count[arr[j]]++;
 
            // If the frequency of 0's is
            // greater than both 1's and 2's
            // then take length of minimum subarray
            if (count[0] > count[1]
                && count[0] > count[2])
                min_len = min(min_len, j - i + 1);
        }
    }
 
    // If min_len == INT_MAX we have no subarray
    // satisfying the condition return -1;
    if (min_len == INT_MAX)
        min_len = -1;
 
    return min_len;
}
 
// Driver Code
int main()
{
 
    // Initializing list of nums
    vector<int> arr = { 2, 0, 2, 0, 1, 2, 2, 2 };
 
    // Call the function and print the answer
    cout << (minLength(arr));
 
    return 0;
}

                    

Java

// Java program for the above approach
import java.util.*;
 
class GFG {
 
    // Function to find the minimum
    // subarray length with most 0's
    static int minLength(ArrayList arr)
    {
        int min_len = Integer.MAX_VALUE;
        int n = arr.size();
 
        // Traverse the array to check
        // the required condition
        for (int i = 0; i < n; i++) {
 
            // Initialize a vector count
            // to store the frequencies
            int[] count = new int[3];
            for (int j = 0; j < 3; j++) {
                count[j] = 0;
            }
 
            int x = (int)arr.get(i);
            count[x]++;
 
            // Check all subarrays of length
            // <=7 and count the frequencies
            for (int j = i + 1; j < Math.min(n, i + 7);
                 j++) {
                int y = (int)arr.get(j);
                count[y]++;
 
                // If the frequency of 0's is
                // greater than both 1's and 2's
                // then take length of minimum subarray
                if (count[0] > count[1]
                    && count[0] > count[2])
                    min_len = Math.min(min_len, j - i + 1);
            }
        }
 
        // If min_len == INT_MAX we have no subarray
        // satisfying the condition return -1;
        if (min_len == Integer.MAX_VALUE)
            min_len = -1;
 
        return min_len;
    }
 
    // Driver Code
    public static void main(String[] args)
    {
        ArrayList<Integer> arr = new ArrayList<Integer>();
 
        arr.add(2);
        arr.add(0);
        arr.add(2);
        arr.add(0);
        arr.add(1);
        arr.add(2);
        arr.add(2);
        arr.add(2);
 
        // Count of isograms in string array arr[]
        System.out.println(minLength(arr));
    }
}
 
// This code is contributed by ukasp.

                    

Python3

# python code for the above approach
INT_MAX = 2147483647
 
# Function to find the minimum
# subarray length with most 0's
def minLength(arr):
 
    min_len = INT_MAX
    n = len(arr)
 
    # Traverse the array to check
    # the required condition
    for i in range(0, n):
 
        # Initialize a vector count
        # to store the frequencies
        count = [0, 0, 0]
        count[arr[i]] += 1
 
        # Check all subarrays of length
        # <=7 and count the frequencies
        for j in range(i+1, min(n, i+7)):
            count[arr[j]] += 1
 
            # If the frequency of 0's is
            # greater than both 1's and 2's
            # then take length of minimum subarray
            if (count[0] > count[1] and count[0] > count[2]):
                min_len = min(min_len, j - i + 1)
 
    # If min_len == INT_MAX we have no subarray
    # satisfying the condition return -1;
    if (min_len == INT_MAX):
        min_len = -1
 
    return min_len
 
# Driver Code
if __name__ == "__main__":
 
    # Initializing list of nums
    arr = [2, 0, 2, 0, 1, 2, 2, 2]
 
    # Call the function and print the answer
    print(minLength(arr))
 
    # This code is contributed by rakeshsahni

                    

C#

// C# program for the above approach
using System;
using System.Collections;
 
class GFG{
 
// Function to find the minimum
// subarray length with most 0's
static int minLength(ArrayList arr)
{
    int min_len = Int32.MaxValue;
    int n = arr.Count;
 
    // Traverse the array to check
    // the required condition
    for (int i = 0; i < n; i++) {
 
        // Initialize a vector count
        // to store the frequencies
        int []count = new int[3];
        for(int j = 0; j < 3; j++) {
            count[j] = 0;
        }
         
        int x = (int)arr[i];
        count[x]++;
 
        // Check all subarrays of length
        // <=7 and count the frequencies
        for (int j = i + 1; j < Math.Min(n, i + 7); j++) {
          int y = (int)arr[j];
            count[y]++;
 
            // If the frequency of 0's is
            // greater than both 1's and 2's
            // then take length of minimum subarray
            if (count[0] > count[1]
                && count[0] > count[2])
                min_len =   Math.Min(min_len, j - i + 1);
        }
    }
 
    // If min_len == INT_MAX we have no subarray
    // satisfying the condition return -1;
    if (min_len == Int32.MaxValue)
        min_len = -1;
 
    return min_len;
}
 
// Driver Code
public static void Main()
{
    ArrayList arr = new ArrayList();
     
    arr.Add(2);
    arr.Add(0);
    arr.Add(2);
    arr.Add(0);
    arr.Add(1);
    arr.Add(2);
    arr.Add(2);
    arr.Add(2);
 
    // Count of isograms in string array arr[]
    Console.WriteLine(minLength(arr));
}
}
 
// This code is contributed by Samim Hossain Mondal.

                    

Javascript

<script>
    // JavaScript code for the above approach
    const INT_MAX = 2147483647
 
    // Function to find the minimum
    // subarray length with most 0's
    const minLength = (arr) => {
        let min_len = INT_MAX;
        let n = arr.length;
 
        // Traverse the array to check
        // the required condition
        for (let i = 0; i < n; i++) {
 
            // Initialize a vector count
            // to store the frequencies
            let count = [0, 0, 0];
            count[arr[i]]++;
 
            // Check all subarrays of length
            // <=7 and count the frequencies
            for (let j = i + 1; j < Math.min(n, i + 7); j++) {
                count[arr[j]]++;
 
                // If the frequency of 0's is
                // greater than both 1's and 2's
                // then take length of minimum subarray
                if (count[0] > count[1]
                    && count[0] > count[2])
                    min_len = Math.min(min_len, j - i + 1);
            }
        }
 
        // If min_len == INT_MAX we have no subarray
        // satisfying the condition return -1;
        if (min_len == INT_MAX)
            min_len = -1;
 
        return min_len;
    }
 
    // Driver Code
 
    // Initializing list of nums
    let arr = [2, 0, 2, 0, 1, 2, 2, 2];
 
    // Call the function and print the answer
    document.write(minLength(arr));
 
    // This code is contributed by rakeshsahni
 
</script>

                    

Output
3

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



Last Updated : 21 Feb, 2023
Like Article
Save Article
Previous
Next
Share your thoughts in the comments
Similar Reads