Open In App

Maximum length of the sub-array whose first and last elements are same

Last Updated : 08 Feb, 2025
Comments
Improve
Suggest changes
Like Article
Like
Report

Given a character array arr[] containing only lowercase English alphabets, the task is to print the maximum length of the subarray such that the first and the last element of the sub-array are same.

Examples: 

Input: arr[] = {‘g’, ‘e’, ‘e’, ‘k’, ‘s’} 
Output:
Explanation: {‘e’, ‘e’} is the maximum length sub-array satisfying the given condition.

Input: arr[] = {‘a’, ‘b’, ‘c’, ‘d’, ‘a’} 
Output:
Explanation: {‘a’, ‘b’, ‘c’, ‘d’, ‘a’} is the required sub-array .

[Naive Approach] Using two nested loops

The idea is to use two nested loops where the outer loop selects each character as a potential start of a subarray, and for each start position, the inner loop searches from the end to find the rightmost occurrence of the same character, keeping track of the maximum length of such subarrays found so far.

C++
// C++ program to find the maximum length
// of the subarray such that the first and
// the last element of the sub-array are same.
#include<iostream>
#include<vector>
using namespace std;

int maxLenSubArray(vector<char> &arr) {
    int n = arr.size();
    
    int res = 0;
    
    // Find the maximum length of 
    // each subarray.
    for (int i=0; i<n; i++) {
        int j;
        
        // Find the furthest index j 
        // such that arr[i]==arr[j].
        for (j=n-1; j>=i; j--) {
            if (arr[i]==arr[j]) break;
        }
        
        // Compare size of current subarray.
        res = max(res, j-i+1);
    }
    
    return res;
}

int main() {

	vector<char> arr = {'g', 'e', 'e', 'k', 's'};
    cout << maxLenSubArray(arr);
	return 0;
}
Java
// Java program to find the maximum length
// of the subarray such that the first and
// the last element of the sub-array are same.
import java.util.*;

class GfG {

    // Function to find the maximum length
    // of the subarray such that the first
    // and the last element of the sub-array are same.
    static int maxLenSubArray(char[] arr) {
        int n = arr.length;

        int res = 0;

        // Find the maximum length of 
        // each subarray.
        for (int i = 0; i < n; i++) {
            int j;

            // Find the furthest index j 
            // such that arr[i] == arr[j].
            for (j = n - 1; j >= i; j--) {
                if (arr[i] == arr[j]) break;
            }

            // Compare size of current subarray.
            res = Math.max(res, j - i + 1);
        }

        return res;
    }

    public static void main(String[] args) {
        char[] arr = {'g', 'e', 'e', 'k', 's'};
        System.out.println(maxLenSubArray(arr));
    }
}
Python
# Python program to find the maximum length
# of the subarray such that the first and
# the last element of the sub-array are same.

# Function to find the maximum length
# of the subarray such that the first
# and the last element of the sub-array are same.
def maxLenSubArray(arr):
    n = len(arr)

    res = 0

    # Find the maximum length of 
    # each subarray.
    for i in range(n):
        j = n - 1

        # Find the furthest index j 
        # such that arr[i] == arr[j].
        while j >= i:
            if arr[i] == arr[j]:
                break
            j -= 1

        # Compare size of current subarray.
        res = max(res, j - i + 1)

    return res

if __name__ == "__main__":
    arr = ['g', 'e', 'e', 'k', 's']
    print(maxLenSubArray(arr))
C#
// C# program to find the maximum length
// of the subarray such that the first and
// the last element of the sub-array are same.
using System;

class GfG {

    // Function to find the maximum length
    // of the subarray such that the first
    // and the last element of the sub-array are same.
    static int maxLenSubArray(char[] arr) {
        int n = arr.Length;

        int res = 0;

        // Find the maximum length of 
        // each subarray.
        for (int i = 0; i < n; i++) {
            int j;

            // Find the furthest index j 
            // such that arr[i] == arr[j].
            for (j = n - 1; j >= i; j--) {
                if (arr[i] == arr[j]) break;
            }

            // Compare size of current subarray.
            res = Math.Max(res, j - i + 1);
        }

        return res;
    }

    static void Main(string[] args) {
        char[] arr = { 'g', 'e', 'e', 'k', 's' };
        Console.WriteLine(maxLenSubArray(arr));
    }
}
JavaScript
// JavaScript program to find the maximum length
// of the subarray such that the first and
// the last element of the sub-array are same.

// Function to find the maximum length
// of the subarray such that the first
// and the last element of the sub-array are same.
function maxLenSubArray(arr) {
    let n = arr.length;

    let res = 0;

    // Find the maximum length of 
    // each subarray.
    for (let i = 0; i < n; i++) {
        let j;

        // Find the furthest index j 
        // such that arr[i] == arr[j].
        for (j = n - 1; j >= i; j--) {
            if (arr[i] === arr[j]) break;
        }

        // Compare size of current subarray.
        res = Math.max(res, j - i + 1);
    }

    return res;
}

const arr = ['g', 'e', 'e', 'k', 's'];
console.log(maxLenSubArray(arr));

Output
2

Time Complexity: O(n^2), as two loops are used.
Auxiliary Space: O(1)

[Efficient Approach] Using Array

The idea is to store the first and last occurrences of each character in separate arrays, and then find the maximum length subarray by calculating the difference between last and first occurrence for each existing character.

Step by step implementation:

  • Initialise two arrays of size 26 (for lowercase letters) to store first and last occurrences, with initial values as -1.
  • Traverse input array once – for each character, update its first occurrence (if not already set) and last occurrence.
  • Find maximum length by checking difference between last and first occurrence for each character that exists in array (first occurrence != -1)
C++
// C++ program to find the maximum length
// of the subarray such that the first and
// the last element of the sub-array are same.
#include<iostream>
#include<vector>
using namespace std;

int maxLenSubArray(vector<char> &arr) {
   int n = arr.size();
   
   // Store first and last occurrence of each character
   vector<int> first(26, -1);
   vector<int> last(26, -1);
   
   // Find first and last occurrence for each character
   for(int i = 0; i < n; i++) {
       int idx = arr[i] - 'a';
       
       // If first occurrence
       if(first[idx] == -1) {
           first[idx] = i;
       }
       
       // Update last occurrence
       last[idx] = i;
   }
   
   // Find max length by checking all characters
   int maxLen = 0;
   for(int i = 0; i < 26; i++) {
       
       // Only consider if character exists in array
       if(first[i] != -1) {
           maxLen = max(maxLen, last[i] - first[i] + 1);
       }
   }
   
   return maxLen;
}

int main() {
   vector<char> arr = {'g', 'e', 'e', 'k', 's'};
   cout << maxLenSubArray(arr);
   return 0;
}
Java
// Java program to find the maximum length
// of the subarray such that the first and
// the last element of the sub-array are same.
import java.util.*;

class GfG {

    static int maxLenSubArray(char[] arr) {
        int n = arr.length;

        // Store first and last occurrence of each character
        int[] first = new int[26];
        int[] last = new int[26];
        Arrays.fill(first, -1);
        Arrays.fill(last, -1);

        // Find first and last occurrence for each character
        for (int i = 0; i < n; i++) {
            int idx = arr[i] - 'a';

            // If first occurrence
            if (first[idx] == -1) {
                first[idx] = i;
            }

            // Update last occurrence
            last[idx] = i;
        }

        // Find max length by checking all characters
        int maxLen = 0;
        for (int i = 0; i < 26; i++) {

            // Only consider if character exists in array
            if (first[i] != -1) {
                maxLen = Math.max(maxLen, last[i] - first[i] + 1);
            }
        }

        return maxLen;
    }

    public static void main(String[] args) {
        char[] arr = {'g', 'e', 'e', 'k', 's'};
        System.out.println(maxLenSubArray(arr));
    }
}
Python
# Python program to find the maximum length
# of the subarray such that the first and
# the last element of the sub-array are same.

def maxLenSubArray(arr):
    n = len(arr)

    # Store first and last occurrence of each character
    first = [-1] * 26
    last = [-1] * 26

    # Find first and last occurrence for each character
    for i in range(n):
        idx = ord(arr[i]) - ord('a')

        # If first occurrence
        if first[idx] == -1:
            first[idx] = i

        # Update last occurrence
        last[idx] = i

    # Find max length by checking all characters
    maxLen = 0
    for i in range(26):

        # Only consider if character exists in array
        if first[i] != -1:
            maxLen = max(maxLen, last[i] - first[i] + 1)

    return maxLen

if __name__ == "__main__":
    arr = ['g', 'e', 'e', 'k', 's']
    print(maxLenSubArray(arr))
C#
// C# program to find the maximum length
// of the subarray such that the first and
// the last element of the sub-array are same.
using System;

class GfG {

    static int maxLenSubArray(char[] arr) {
        int n = arr.Length;

        // Store first and last occurrence of each character
        int[] first = new int[26];
        int[] last = new int[26];
        Array.Fill(first, -1);
        Array.Fill(last, -1);

        // Find first and last occurrence for each character
        for (int i = 0; i < n; i++) {
            int idx = arr[i] - 'a';

            // If first occurrence
            if (first[idx] == -1) {
                first[idx] = i;
            }

            // Update last occurrence
            last[idx] = i;
        }

        // Find max length by checking all characters
        int maxLen = 0;
        for (int i = 0; i < 26; i++) {

            // Only consider if character exists in array
            if (first[i] != -1) {
                maxLen = Math.Max(maxLen, last[i] - first[i] + 1);
            }
        }

        return maxLen;
    }

    static void Main(string[] args) {
        char[] arr = { 'g', 'e', 'e', 'k', 's' };
        Console.WriteLine(maxLenSubArray(arr));
    }
}
JavaScript
// JavaScript program to find the maximum length
// of the subarray such that the first and
// the last element of the sub-array are same.

function maxLenSubArray(arr) {
    let n = arr.length;

    // Store first and last occurrence of each character
    let first = new Array(26).fill(-1);
    let last = new Array(26).fill(-1);

    // Find first and last occurrence for each character
    for (let i = 0; i < n; i++) {
        let idx = arr[i].charCodeAt(0) - 'a'.charCodeAt(0);

        // If first occurrence
        if (first[idx] === -1) {
            first[idx] = i;
        }

        // Update last occurrence
        last[idx] = i;
    }

    // Find max length by checking all characters
    let maxLen = 0;
    for (let i = 0; i < 26; i++) {

        // Only consider if character exists in array
        if (first[i] !== -1) {
            maxLen = Math.max(maxLen, last[i] - first[i] + 1);
        }
    }

    return maxLen;
}

const arr = ['g', 'e', 'e', 'k', 's'];
console.log(maxLenSubArray(arr));

Output
2

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

Related Topic: Subarrays, Subsequences, and Subsets in Array



Next Article
Article Tags :
Practice Tags :

Similar Reads