Skip to content
Related Articles

Related Articles

Improve Article
Save Article
Like Article

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

  • Last Updated : 23 Dec, 2021

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 the 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.

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) 


My Personal Notes arrow_drop_up
Recommended Articles
Page :

Start Your Coding Journey Now!