Find the maximum length of the prefix
Last Updated :
20 Sep, 2023
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
#include <bits/stdc++.h>
using namespace std;
int Maximum_Length(vector< int > a)
{
int counts[11] = {0};
int ans = 0;
for ( int index = 0;
index < a.size();
index++)
{
counts[a[index]] += 1;
vector< int > k;
for ( auto i : counts)
if (i != 0)
k.push_back(i);
sort(k.begin(), k.end());
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 ans + 1;
}
int main()
{
vector< int > a = { 1, 1, 1, 2, 2, 2 };
cout << (Maximum_Length(a));
}
|
Java
import java.util.*;
public class Main
{
public static int Maximum_Length(Vector<Integer> a)
{
int [] counts = new int [ 11 ];
int ans = 0 ;
for ( int index = 0 ;
index < a.size();
index++)
{
counts[a.get(index)] += 1 ;
Vector<Integer> k = new Vector<Integer>();
for ( int i : counts)
if (i != 0 )
k.add(i);
Collections.sort(k);
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 ans + 1 ;
}
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));
}
}
|
Python3
def Maximum_Length(a):
counts = [ 0 ] * 11
for index, v in enumerate (a):
counts[v] + = 1
k = sorted ([i for i in counts if i])
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 ans + 1
if __name__ = = "__main__" :
a = [ 1 , 1 , 1 , 2 , 2 , 2 ]
n = len (a)
print (Maximum_Length(a))
|
C#
using System;
using System.Collections.Generic;
class GFG {
static int Maximum_Length(List< int > a)
{
int [] counts = new int [11];
int ans = 0;
for ( int index = 0;
index < a.Count;
index++)
{
counts[a[index]] += 1;
List< int > k = new List< int >();
foreach ( int i in counts)
if (i != 0)
k.Add(i);
k.Sort();
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 ans + 1;
}
static void Main() {
List< int > a = new List< int >( new int []{ 1, 1, 1, 2, 2, 2 });
Console.Write(Maximum_Length(a));
}
}
|
Javascript
<script>
function Maximum_Length(a)
{
let counts = new Array(11);
counts.fill(0);
let ans = 0;
for (let index = 0; index < a.length; index++)
{
counts[a[index]] += 1;
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 (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 (ans);
}
let a = [ 1, 1, 1, 2, 2, 2 ];
document.write(Maximum_Length(a));
</script>
|
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.
C++
#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;
}
|
C
#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;
}
|
Java
public 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].charAt(prefixLen)
== strings[ 0 ].charAt(prefixLen)) {
prefixLen++;
}
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);
}
}
|
Python3
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)
|
C#
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
function max_prefix_length(strings, num_strings) {
let max_prefix = strings[0].length;
for (let i = 1; i < num_strings; i++) {
let 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;
}
let strings = [ "hello" , "hell" , "help" , "helm" , "he" ];
let num_strings = 5;
let max_prefix = max_prefix_length(strings, num_strings);
console.log( "The maximum prefix length is " + max_prefix);
|
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.
Share your thoughts in the comments
Please Login to comment...