Find the maximum length of the prefix

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:

filter_none

edit
close

play_arrow

link
brightness_4
code

# 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))

chevron_right


Output:

5


My Personal Notes arrow_drop_up

Check out this Author's contributed articles.

If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.

Please Improve this article if you find anything incorrect by clicking on the "Improve Article" button below.