Find the maximum length of the prefix - GeeksforGeeks

13 Apr, 2021
Given an array arr[] of N integers where all elements of the array are from the range [0, 9] i.e. a single digit, the task is to find the maximum length of the prefix of this array such that removing exactly one element from the prefix will make the occurrence of the remaining elements in the prefix same.Examples: 
Input: arr[] = {1, 1, 1, 2, 2, 2} Output: 5 Required prefix is {1, 1, 1, 2, 2} After removing 1, every element will have equal frequency i.e. {1, 1, 2, 2}
Input: arr[] = {1, 1, 1, 2, 2, 2, 3, 3, 3, 4, 4, 4, 5} Output: 13
Input: arr[] = {10, 2, 5, 4, 1} Output: 5 
Approach: Iterate over all the prefixes and check for each prefix if we can remove an element so that each element has same occurrence. In order to satisfy this condition, one of the following conditions must hold true: 
There is only one element in the prefix.
All the elements in the prefix have the occurrence of 1.
Every element has the same occurrence, except for exactly one element which has occurrence of 1.
Every element has the same occurrence, except for exactly one element which has the occurrence exactly 1 more than any other elements.
Below is the implementation of the above approach:
C++14
Java
Python3
C#
Javascript
// C++ implementation of the approach#include <bits/stdc++.h>using namespace std; // Function to return the maximum// length of the required prefixint Maximum_Length(vector<int> a){         // Array to store the frequency    // of each element of the array    int counts[11] = {0};     // Iterating for all the elements    int ans = 0;    for(int index = 0;            index < a.size();            index++)    {                 // Update the frequency of the        // current element i.e. v        counts[a[index]] += 1;         // Sorted positive values        // from counts array        vector<int> k;        for(auto i : counts)            if (i != 0)                k.push_back(i);         sort(k.begin(), k.end());         // If current prefix satisfies        // the given conditions        if (k.size() == 1 ||           (k[0] == k[k.size() - 2] &&            k.back() - k[k.size() - 2] == 1) ||           (k[0] == 1 and k[1] == k.back()))            ans = index;    }         // Return the maximum length    return ans + 1;} // Driver codeint main(){    vector<int> a = { 1, 1, 1, 2, 2, 2 };     cout << (Maximum_Length(a));} // This code is contributed by grand_master
// Java implementation of the approachimport java.util.*;public class Main{    // Function to return the maximum    // length of the required prefix    public static int Maximum_Length(Vector<Integer> a)    {                   // Array to store the frequency        // of each element of the array        int[] counts = new int[11];               // Iterating for all the elements        int ans = 0;        for(int index = 0;                index < a.size();                index++)        {                           // Update the frequency of the            // current element i.e. v            counts[a.get(index)] += 1;                   // Sorted positive values            // from counts array            Vector<Integer> k = new Vector<Integer>();            for(int i : counts)                if (i != 0)                    k.add(i);                   Collections.sort(k);                    // If current prefix satisfies            // the given conditions            if (k.size() == 1 ||               (k.get(0) == k.get(k.size() - 2) &&                k.get(k.size() - 1) - k.get(k.size() - 2) == 1) ||               (k.get(0) == 1 && k.get(1) == k.get(k.size() - 1)))                ans = index;        }                   // Return the maximum length        return ans + 1;    }         // Driver code    public static void main(String[] args) {        Vector<Integer> a = new Vector<Integer>();        a.add(1);        a.add(1);        a.add(1);        a.add(2);        a.add(2);        a.add(2);                System.out.println(Maximum_Length(a));    }} // This code is contributed by divyeshrabadiya07
# Python3 implementation of the approach # Function to return the maximum# length of the required prefixdef Maximum_Length(a):     # Array to store the frequency    # of each element of the array    counts =[0]*11     # Iterating for all the elements    for index, v in enumerate(a):         # Update the frequency of the        # current element i.e. v        counts[v] += 1         # Sorted positive values from counts array        k = sorted([i for i in counts if i])         # If current prefix satisfies        # the given conditions        if len(k)== 1 or (k[0]== k[-2] and k[-1]-k[-2]== 1) or (k[0]== 1 and k[1]== k[-1]):            ans = index     # Return the maximum length    return ans + 1 # Driver codeif __name__=="__main__":    a = [1, 1, 1, 2, 2, 2]    n = len(a)    print(Maximum_Length(a))
// C# implementation of the approachusing System;using System.Collections.Generic;class GFG {         // Function to return the maximum    // length of the required prefix    static int Maximum_Length(List<int> a)    {                  // Array to store the frequency        // of each element of the array        int[] counts = new int[11];              // Iterating for all the elements        int ans = 0;        for(int index = 0;                index < a.Count;                index++)        {                          // Update the frequency of the            // current element i.e. v            counts[a[index]] += 1;                  // Sorted positive values            // from counts array            List<int> k = new List<int>();            foreach(int i in counts)                if (i != 0)                    k.Add(i);                  k.Sort();                  // If current prefix satisfies            // the given conditions            if (k.Count == 1 ||               (k[0] == k[k.Count - 2] &&                k[k.Count - 1] - k[k.Count - 2] == 1) ||               (k[0] == 1 && k[1] == k[k.Count - 1]))                ans = index;        }                  // Return the maximum length        return ans + 1;    }   static void Main() {    List<int> a = new List<int>(new int[]{ 1, 1, 1, 2, 2, 2 });    Console.Write(Maximum_Length(a));  }} // This code is contributed by divyesh072019
<script>    // Javascript implementation of the approach         // Function to return the maximum    // length of the required prefix    function Maximum_Length(a)    {                   // Array to store the frequency        // of each element of the array        let counts = new Array(11);        counts.fill(0);               // Iterating for all the elements        let ans = 0;        for(let index = 0; index < a.length; index++)        {                           // Update the frequency of the            // current element i.e. v            counts[a[index]] += 1;                   // Sorted positive values            // from counts array            let k = [];            for(let i = 0; i < counts.length; i++)            {                if (counts[i] != 0)                {                    k.push(i);                }            }                   k.sort(function(a, b){return a - b});                   // If current prefix satisfies            // the given conditions            if (k.length == 1 ||               (k[0] == k[k.length - 2] &&                k[k.length - 1] - k[k.length - 2] == 1) ||               (k[0] == 1 && k[1] == k[k.length - 1]))                ans = index;        }                   // Return the maximum length        return (ans);    }           let a = [ 1, 1, 1, 2, 2, 2 ];    document.write(Maximum_Length(a));               // This code is contributed by suresh07.</script>
  
5
 
 
grand_master
divyesh072019
divyeshrabadiya07
suresh07
Arrays
frequency-counting
prefix
Arrays
Mathematical
Arrays
Mathematical
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Count pairs with given sum
Chocolate Distribution Problem
Window Sliding Technique
Reversal algorithm for array rotation
Next Greater Element
Program for Fibonacci numbers
Write a program to print all permutations of a given string
C++ Data Types
Set in C++ Standard Template Library (STL)
Coin Change | DP-7