Open In App

Maximum length of subarray consisting of same type of element on both halves of sub-array

Last Updated : 26 Apr, 2023
Improve
Improve
Like Article
Like
Save
Share
Report

Given an array arr[] of N integers, the task is to find the maximum length of sub-array consisting of the same type of element on both halves of the sub-array. Also, the elements on both halves differ from each other.

Examples:

Input: arr[] = {2, 3, 4, 4, 5, 5, 6, 7, 8, 10}
Output: 4
Explanation:
{2, 3}, {3, 4}, {4, 4, 5, 5}, {5, 6}, etc, are the valid sub-arrays where both halves have only one type of element. 
{4, 4, 5, 5} is the sub-array having maximum length.
Hence, the output is 4. 

Input: arr[] = {1, 7, 7, 10, 10, 7, 7, 7, 8, 8, 8, 9}
Output: 6
Explanation:
{1, 7}, {7, 7, 10, 10}, {7, 7, 7, 8, 8, 8}, {8, 9}, etc, are the valid sub-arrays where both halves have only one type of element. 
{7, 7, 7, 8, 8, 8} is the sub-array having maximum length.
Hence, the output is 6. 

 

Naive Approach: The naive idea is to generate all possible subarray and check any subarray with maximum length can be divided into two halves such that all the elements in both the halves are the same.

Time Complexity: O(N3)
Auxiliary Space: O(1)

Efficient Approach: To solve this problem the idea is to use the concept of Prefix Sum. Follow the steps below to solve the problem: 

  1. Traverse the array from the start in the forward direction and store the continuous occurrence of an integer for each index in an array forward[].
  2. Similarly, traverse the array from the end in the reverse direction and store the continuous occurrence of an integer for each index in an array backward[].
  3. Store the maximum of min(forward[i], backward[i+1])*2, for all the index where arr[i]!=arr[i+1].
  4. Print the value obtained in the above step.

Below is the implementation of the above approach:

C++




// C++ program for the above approach
#include <bits/stdc++.h>
using namespace std;
 
// Function that finds the maximum
// length of the sub-array that
// contains equal element on both
// halves of sub-array
void maxLengthSubArray(int A[], int N)
{
 
    // To store continuous occurrence
    // of the element
    int forward[N], backward[N];
 
    // To store continuous
    // forward occurrence
    for (int i = 0; i < N; i++) {
 
        if (i == 0
            || A[i] != A[i - 1]) {
            forward[i] = 1;
        }
        else
            forward[i] = forward[i - 1] + 1;
    }
 
    // To store continuous
    // backward occurrence
    for (int i = N - 1; i >= 0; i--) {
 
        if (i == N - 1
            || A[i] != A[i + 1]) {
            backward[i] = 1;
        }
        else
            backward[i] = backward[i + 1] + 1;
    }
 
    // To store the maximum length
    int ans = 0;
 
    // Find maximum length
    for (int i = 0; i < N - 1; i++) {
 
        if (A[i] != A[i + 1])
            ans = max(ans,
                    min(forward[i],
                        backward[i + 1])
                        * 2);
    }
 
    // Print the result
    cout << ans;
}
 
// Driver Code
int main()
{
    // Given array
    int arr[] = { 1, 2, 3, 4, 4,
                4, 6, 6, 6, 9 };
 
    // Size of the array
    int N = sizeof(arr) / sizeof(arr[0]);
 
    // Function Call
    maxLengthSubArray(arr, N);
    return 0;
}


Java




// Java program for the above approach         
class GFG{         
            
// Function that finds the maximum         
// length of the sub-array that         
// contains equal element on both         
// halves of sub-array         
static void maxLengthSubArray(int A[], int N)         
{
     
    // To store continuous occurrence         
    // of the element         
    int forward[] = new int[N];         
    int backward[] = new int[N];         
     
    // To store continuous         
    // forkward occurrence         
    for(int i = 0; i < N; i++)
    {
        if (i == 0 || A[i] != A[i - 1])
        {         
            forward[i] = 1;         
        }         
        else         
            forward[i] = forward[i - 1] + 1;         
    }         
     
    // To store continuous         
    // backward occurrence         
    for(int i = N - 1; i >= 0; i--)
    {
        if (i == N - 1 || A[i] != A[i + 1])
        {         
            backward[i] = 1;         
        }         
        else         
            backward[i] = backward[i + 1] + 1;         
    }         
            
    // To store the maximum length         
    int ans = 0;         
        
    // Find maximum length         
    for(int i = 0; i < N - 1; i++)
    {         
        if (A[i] != A[i + 1])         
            ans = Math.max(ans,         
                           Math.min(forward[i],         
                                    backward[i + 1]) * 2);         
    }         
     
    // Print the result         
    System.out.println(ans);         
}         
            
// Driver Code         
public static void main(String[] args)
{         
     
    // Given array         
    int arr[] = { 1, 2, 3, 4, 4,         
                  4, 6, 6, 6, 9 };         
            
    // Size of the array         
    int N = arr.length;         
            
    // Function call         
    maxLengthSubArray(arr, N);         
}         
}
 
// This code is contributed by rutvik_56


Python3




# Python3 program for the above approach
 
# Function that finds the maximum
# length of the sub-array that
# contains equal element on both
# halves of sub-array
def maxLengthSubArray(A, N):
 
    # To store continuous occurrence
    # of the element
    forward = [0] * N
    backward = [0] * N
 
    # To store continuous
    # forward occurrence
    for i in range(N):
            if i == 0 or A[i] != A[i - 1]:
                forward[i] = 1
            else:
                forward[i] = forward[i - 1] + 1
 
    # To store continuous
    # backward occurrence
    for i in range(N - 1, -1, -1):
        if i == N - 1 or A[i] != A[i + 1]:
            backward[i] = 1
        else:
            backward[i] = backward[i + 1] + 1
             
    # To store the maximum length
    ans = 0
 
    # Find maximum length
    for i in range(N - 1):
        if (A[i] != A[i + 1]):
            ans = max(ans,
                    min(forward[i],
                        backward[i + 1]) * 2);
 
    # Print the result
    print(ans)
 
# Driver Code
 
# Given array
arr = [ 1, 2, 3, 4, 4, 4, 6, 6, 6, 9 ]
 
# Size of the array
N = len(arr)
 
# Function call
maxLengthSubArray(arr, N)
 
# This code is contributed by yatinagg


C#




// C# program for the above approach         
using System;
class GFG{         
            
// Function that finds the maximum         
// length of the sub-array that         
// contains equal element on both         
// halves of sub-array         
static void maxLengthSubArray(int []A, int N)         
{
     
    // To store continuous occurrence         
    // of the element         
    int []forward = new int[N];         
    int []backward = new int[N];         
     
    // To store continuous         
    // forkward occurrence         
    for(int i = 0; i < N; i++)
    {
        if (i == 0 || A[i] != A[i - 1])
        {         
            forward[i] = 1;         
        }         
        else         
            forward[i] = forward[i - 1] + 1;         
    }         
     
    // To store continuous         
    // backward occurrence         
    for(int i = N - 1; i >= 0; i--)
    {
        if (i == N - 1 || A[i] != A[i + 1])
        {         
            backward[i] = 1;         
        }         
        else         
            backward[i] = backward[i + 1] + 1;         
    }         
            
    // To store the maximum length         
    int ans = 0;         
        
    // Find maximum length         
    for(int i = 0; i < N - 1; i++)
    {         
        if (A[i] != A[i + 1])         
            ans = Math.Max(ans,         
                           Math.Min(forward[i],         
                                    backward[i + 1]) * 2);         
    }         
     
    // Print the result         
    Console.WriteLine(ans);         
}         
            
// Driver Code         
public static void Main(String[] args)
{         
     
    // Given array         
    int []arr = { 1, 2, 3, 4, 4,         
                  4, 6, 6, 6, 9 };         
            
    // Size of the array         
    int N = arr.Length;         
            
    // Function call         
    maxLengthSubArray(arr, N);         
}         
}
 
// This code is contributed by Princi Singh


Javascript




<script>
 
// Javascript program for the above approach
 
// Function that finds the maximum        
// length of the sub-array that        
// contains equal element on both        
// halves of sub-array        
function maxLengthSubArray(A, N)        
{
      
    // To store continuous occurrence        
    // of the element        
    let forward = Array.from({length: N}, (_, i) => 0);       
    let backward = Array.from({length: N}, (_, i) => 0);   
      
    // To store continuous        
    // forkward occurrence        
    for(let i = 0; i < N; i++)
    {
        if (i == 0 || A[i] != A[i - 1])
        {        
            forward[i] = 1;        
        }        
        else        
            forward[i] = forward[i - 1] + 1;        
    }        
      
    // To store continuous        
    // backward occurrence        
    for(let i = N - 1; i >= 0; i--)
    {
        if (i == N - 1 || A[i] != A[i + 1])
        {        
            backward[i] = 1;        
        }        
        else        
            backward[i] = backward[i + 1] + 1;        
    }        
             
    // To store the maximum length        
    let ans = 0;        
         
    // Find maximum length        
    for(let i = 0; i < N - 1; i++)
    {        
        if (A[i] != A[i + 1])        
            ans = Math.max(ans,        
                           Math.min(forward[i],        
                                    backward[i + 1]) * 2);        
    }        
      
    // Print the result        
    document.write(ans);        
}        
    
 
// Driver Code
     
    // Given array        
    let arr = [ 1, 2, 3, 4, 4,        
                  4, 6, 6, 6, 9 ];        
             
    // Size of the array        
    let N = arr.length;        
             
    // Function call        
    maxLengthSubArray(arr, N);
 
</script>


Output: 

6

 

Time Complexity: O(N)
Auxiliary Space: O(N)



Previous Article
Next Article

Similar Reads

Maximum sum of K-length subarray consisting of same number of distinct elements as the given array
Given an array arr[] consisting of N integers and an integer K, the task is to find a subarray of size K with maximum sum and count of distinct elements same as that of the original array. Examples: Input: arr[] = {7, 7, 2, 4, 2, 7, 4, 6, 6, 6}, K = 6Output: 31Explanation: The given array consists of 4 distinct elements, i.e. {2, 4, 6, 7}. The suba
16 min read
Maximum count of sub-strings of length K consisting of same characters
Given a string str and an integer k. The task is to count the occurrences of sub-strings of length k that consist of the same characters. There can be multiple such sub-strings possible of length k, choose the count of the one which appears the maximum number of times as the sub-string (non-overlapping) of str. Examples: Input: str = "aaacaabbaa",
6 min read
Check if both halves of the string have same set of characters in Python
Given a string of lowercase characters only, the task is to check if it is possible to split a string from middle which will gives two halves having the same characters and same frequency of each character. If the length of the given string is ODD then ignore the middle element and check for the rest. Examples: Input : abbaab Output : NO The two ha
3 min read
Check if both halves of the string have same set of characters
Given a string of lowercase characters only, the task is to check if it is possible to split a string from the middle which will give two halves having the same characters and same frequency of each character. If the length of the given string is ODD then ignore the middle element and check for the rest. Examples: Input: abbaab Output: NO The two h
12 min read
All possible binary numbers of length n with equal sum in both halves
Given a number n, we need to print all n-digit binary numbers with equal sum in left and right halves. If n is odd, then mid element can be either 0 or 1. Examples: Input : n = 4 Output : 0000 0101 0110 1001 1010 1111 Input : n = 5 Output : 00000 00100 01001 01101 01010 01110 10001 10101 10010 10110 11011 11111 The idea is to recursively build left
10 min read
Maximize length of longest subarray consisting of same elements by at most K decrements
Given an array arr[] of size N and an integer K, the task is to find the length of the longest subarray consisting of same elements that can be obtained by decrementing the array elements by 1 at most K times. Example: Input: arr[] = { 1, 2, 3 }, K = 1Output: 2Explanation:Decrementing arr[0] by 1 modifies arr[] to { 1, 1, 3 }The longest subarray wi
19 min read
Length of the smallest sub-string consisting of maximum distinct characters
Given a string of length N, find the length of the smallest sub-string consisting of maximum distinct characters. Note : Our output can have same character. Examples: Input : "AABBBCBB" Output : 5 Input : "AABBBCBBAC" Output : 3 Explanation : Sub-string -&gt; "BAC" Input : "GEEKSGEEKSFOR" Output : 8 Explanation : Sub-string -&gt; "GEEKSFOR"Recommen
17 min read
Count the number of sub-arrays such that the average of elements present in the sub-array is greater than that not present in the sub-array
Given an array of integers arr[], the task is to count the number of sub-arrays such that the average of elements present in the sub-array is greater than the average of elements that are not present in the sub-array.Examples: Input: arr[] = {6, 3, 5} Output: 3 The sub-arrays are {6}, {5} and {6, 3, 5} because their averages are greater than {3, 5}
8 min read
Length of smallest subarray consisting of all occurrences of all maximum occurring elements
Given an array arr[] of size N, The task is to find the length of the smallest subarray consisting of all the occurrences of maximum occurring elementsExamples: Input: arr[] = {1, 2, 1, 3, 2}Output: 5Explanation: Elements with maximum frequency (=2) are 1 &amp; 2. Therefore, the length of smallest subarray consisting of all the occurrences of 1 and
6 min read
Check if both halves of the string have at least one different character
Earlier we have discussed on how to check if both halves of the string have same set of characters. Now, we further extend our problem on checking if both halves of the string have at least one different character. Examples: Input : baaaabOutput: No, both halves do not differ at allThe two halves contain the same characters and their frequencies ma
15 min read