Find the maximum length of the prefix

• Last Updated : 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:
Required prefix is {1, 1, 1, 2, 2}
After removing 1, every element will have equal frequency i.e. {1, 1, 2, 2}

Attention reader! Don’t stop learning now. Get hold of all the important DSA concepts with the DSA Self Paced Course at a student-friendly price and become industry ready.  To complete your preparation from learning a language to DS Algo and many more,  please refer Complete Interview Preparation Course.

In case you wish to attend live classes with experts, please refer DSA Live Classes for Working Professionals and Competitive Programming Live for Students.

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:

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

 `// C++ implementation of the approach``#include ``using` `namespace` `std;` `// Function to return the maximum``// length of the required prefix``int` `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 code``int` `main()``{``    ``vector<``int``> a = { 1, 1, 1, 2, 2, 2 };` `    ``cout << (Maximum_Length(a));``}` `// This code is contributed by grand_master`

Java

 `// Java implementation of the approach``import` `java.util.*;``public` `class` `Main``{``    ``// Function to return the maximum``    ``// length of the required prefix``    ``public` `static` `int` `Maximum_Length(Vector 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 k = ``new` `Vector();``            ``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 a = ``new` `Vector();``        ``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

 `# Python3 implementation of the approach` `# Function to return the maximum``# length of the required prefix``def` `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 code``if` `__name__``=``=``"__main__"``:``    ``a ``=` `[``1``, ``1``, ``1``, ``2``, ``2``, ``2``]``    ``n ``=` `len``(a)``    ``print``(Maximum_Length(a))`

C#

 `// C# implementation of the approach``using` `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`

Javascript

 ``

Output:
`5`

My Personal Notes arrow_drop_up