Open In App

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:
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:

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: 

Below is the implementation of the above approach:




// C++ implementation of the approach
#include <bits/stdc++.h>
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 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<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 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# 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




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

 
 

Output
5

Time Complexity: O(aloga * a) where a is the length of the array

Auxiliary Space: O(a) where a is the length of the array

Approach:

1. Initialize the maximum prefix length to be the length of the first string in the set.
2. Compare the first character of each subsequent string with the corresponding character of the first string.
3. If the characters match, increment a prefix counter.
4. If the characters do not match, update the maximum prefix length to be the minimum of the current maximum prefix length and the prefix counter.
5. Repeat steps 2-4 for all strings in the set.
6. The final maximum prefix length is the result.




#include <bits/stdc++.h>
using namespace std;
 
int max_prefix_length(char** strings, int num_strings) {
    int max_prefix = std::strlen(strings[0]);
    for (int i = 1; i < num_strings; i++) {
        int prefix_len = 0;
        while (strings[i][prefix_len] == strings[0][prefix_len]) {
            prefix_len++;
        }
        max_prefix = (prefix_len < max_prefix) ? prefix_len : max_prefix;
    }
    return max_prefix;
}
 
int main() {
    char* strings[] = {"hello", "hell", "help", "helm", "he"};
    int num_strings = 5;
    int max_prefix = max_prefix_length(strings, num_strings);
    cout << "The maximum prefix length is " << max_prefix << std::endl;
    return 0;
}




#include <stdio.h>
#include <string.h>
 
int max_prefix_length(char** strings, int num_strings) {
    int max_prefix = strlen(strings[0]);
    for (int i = 1; i < num_strings; i++) {
        int prefix_len = 0;
        while (strings[i][prefix_len] == strings[0][prefix_len]) {
            prefix_len++;
        }
        max_prefix = (prefix_len < max_prefix) ? prefix_len : max_prefix;
    }
    return max_prefix;
}
 
int main() {
    char* strings[] = {"hello", "hell", "help", "helm", "he"};
    int num_strings = 5;
    int max_prefix = max_prefix_length(strings, num_strings);
    printf("The maximum prefix length is %d\n", max_prefix);
    return 0;
}




public class Program {
   // A function which calculates maximum prefix length.
  static int maxPrefixLength(String[] strings) {
       
        // make first string length as max_prefix
        int maxPrefix = strings[0].length();
        for (int i = 1; i < strings.length; i++) {
             
             // calculate for curr prefix length.
            int prefixLen = 0;
            while (prefixLen < strings[i].length()
                   && prefixLen < strings[0].length()
                   && strings[i].charAt(prefixLen)
                          == strings[0].charAt(prefixLen)) {
                prefixLen++;
            }
             // update max prefix if prefix length is less than max_prefix.
            maxPrefix = Math.min(maxPrefix, prefixLen);
        }
        return maxPrefix;
    }
 
    public static void main(String[] args) {
        String[] strings = { "hello", "hell", "help", "helm", "he" };
        int maxPrefix = maxPrefixLength(strings);
        System.out.printf("The maximum prefix length is %d%n", maxPrefix);
    }
}




def max_prefix_length(strings):
    max_prefix = len(strings[0])
    for i in range(1, len(strings)):
        prefix_len = 0
        while (prefix_len < len(strings[i])
               and prefix_len < len(strings[0])
               and strings[i][prefix_len]
                      == strings[0][prefix_len]):
            prefix_len += 1
        max_prefix = min(max_prefix, prefix_len)
    return max_prefix
 
strings = ["hello", "hell", "help", "helm", "he"]
max_prefix = max_prefix_length(strings)
print("The maximum prefix length is", max_prefix)




using System;
 
class Program {
    static int MaxPrefixLength(string[] strings)
    {
        int maxPrefix = strings[0].Length;
        for (int i = 1; i < strings.Length; i++) {
            int prefixLen = 0;
            while (prefixLen < strings[i].Length
                   && prefixLen < strings[0].Length
                   && strings[i][prefixLen]
                          == strings[0][prefixLen]) {
                prefixLen++;
            }
            maxPrefix = Math.Min(maxPrefix, prefixLen);
        }
        return maxPrefix;
    }
 
    static void Main()
    {
        string[] strings
            = { "hello", "hell", "help", "helm", "he" };
        int maxPrefix = MaxPrefixLength(strings);
        Console.WriteLine(
            "The maximum prefix length is {0}", maxPrefix);
    }
}




// Javascript code addition
 
// A function which calculates maximum prefix length.
function max_prefix_length(strings, num_strings) {
     
    // make first string length as max_prefix
    let max_prefix = strings[0].length;
     
    for (let i = 1; i < num_strings; i++) {
         
        // calculate for curr prefix length.
        let prefix_len = 0;
        while (strings[i][prefix_len] == strings[0][prefix_len]) {
            prefix_len++;
        }
         
        // update max prefix if prefix length is less than max_prefix.
        max_prefix = (prefix_len < max_prefix) ? prefix_len : max_prefix;
    }
    return max_prefix;
}
 
// Declare a strings array
let strings = ["hello", "hell", "help", "helm", "he"];
 
// size of strings array
let num_strings = 5;
 
// calculating max prefix length
let max_prefix = max_prefix_length(strings, num_strings);
 
// printing the maximum prefix length
console.log("The maximum prefix length is " + max_prefix);
 
// The code is contributed by Nidhi goel.

Output
The maximum prefix length is 2

Time complexity: O(N*M), where N is the number of strings and M is the length of the longest string in the set.
Space complexity: O(1), as we only use a fixed number of variables regardless of the size of the input.

 


Article Tags :