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

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: 2
{‘e’, ‘e’} is the maximum length sub-array satisfying the given condition.

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

Approach: For every element of the array ch, store it’s first and last occurrence. Then the maximum length of the sub-array that starts and ends with the same element ch will be lastOccurrence(ch) – firstOccurrence(ch) + 1. The maximum of this value among all the elements is the required answer.

Below is the implementation of the above approach:

Java

filter_none

edit
close

play_arrow

link
brightness_4
code

// Java implementation of the approach
  
// Class that represents a single element
// of the given array and stores it's first
// and the last occurrence in the array
class Element {
    int firstOcc, lastOcc;
  
    public Element()
    {
        firstOcc = lastOcc = -1;
    }
  
    // Function to update the occurrence
    // of a particular character in the array
    public void updateOccurrence(int index)
    {
  
        // If first occurrence is set to something
        // other than -1 then it doesn't need updating
        if (firstOcc == -1)
            firstOcc = index;
  
        // Last occurrence will be updated everytime
        // the character appears in the array
        lastOcc = index;
    }
}
  
class GFG {
  
    // Function to return the maximum length of the
    // sub-array that starts and ends with the same element
    public static int maxLenSubArr(char arr[], int n)
    {
  
        Element elements[] = new Element[26];
        for (int i = 0; i < n; i++) {
            int ch = arr[i] - 'a';
  
            // Initialize the current character
            // if haven't already
            if (elements[ch] == null)
                elements[ch] = new Element();
  
            // Update current character's occurrence
            elements[ch].updateOccurrence(i);
        }
  
        int maxLen = 0;
        for (int i = 0; i < 26; i++) {
  
            // If current character appears in the given array
            if (elements[i] != null) {
  
                // Length of the longest sub-array that starts
                // and ends with the same element
                int len = elements[i].lastOcc - elements[i].firstOcc + 1;
                maxLen = Math.max(maxLen, len);
            }
        }
  
        // Return the maximum length of
        // the required sub-array
        return maxLen;
    }
  
    // Driver code
    public static void main(String[] args)
    {
        char arr[] = { 'g', 'e', 'e', 'k', 's' };
        int n = arr.length;
  
        System.out.print(maxLenSubArr(arr, n));
    }
}

chevron_right


Python3

filter_none

edit
close

play_arrow

link
brightness_4
code

# Python3 implementation of the approach 
  
# Class that represents a single element 
# of the given array and stores it's first 
# and the last occurrence in the array 
class Element: 
      
    def __init__(self):
        self.firstOcc = -1
        self.lastOcc = -1
  
    # Function to update the occurrence 
    # of a particular character in the array 
    def updateOccurrence(self, index): 
  
        # If first occurrence is set to 
        # something other than -1 then it
        # doesn't need updating 
        if self.firstOcc == -1
            self.firstOcc = index 
  
        # Last occurrence will be updated 
        # everytime the character appears
        # in the array 
        self.lastOcc = index 
  
# Function to return the maximum length 
# of the sub-array that starts and ends
# with the same element 
def maxLenSubArr(arr, n): 
  
    elements = [None] * 26
    for i in range(0, n): 
        ch = ord(arr[i]) - ord('a'
  
        # Initialize the current character 
        # if haven't already 
        if elements[ch] == None
            elements[ch] = Element() 
  
        # Update current character's occurrence 
        elements[ch].updateOccurrence(i) 
          
    maxLen = 0
    for i in range(0, 26): 
  
        # If current character appears in
        # the given array 
        if elements[i] != None
  
            # Length of the longest sub-array that 
            # starts and ends with the same element 
            length = (elements[i].lastOcc - 
                      elements[i].firstOcc + 1)
            maxLen = max(maxLen, length) 
              
    # Return the maximum length of 
    # the required sub-array 
    return maxLen 
      
# Driver code 
if __name__ == "__main__":
      
    arr = ['g', 'e', 'e', 'k', 's'
    n = len(arr) 
  
    print(maxLenSubArr(arr, n)) 
      
# This code is contributed by Rituraj Jain

chevron_right


C#

filter_none

edit
close

play_arrow

link
brightness_4
code

// C# implementation of the above approach 
using System;
  
// Class that represents a single element 
// of the given array and stores it's first 
// and the last occurrence in the array 
public class Element 
      
    public int firstOcc, lastOcc; 
  
    public Element() 
    
        firstOcc = lastOcc = -1; 
    
  
    // Function to update the occurrence 
    // of a particular character in the array 
    public void updateOccurrence(int index) 
    
  
        // If first occurrence is set to something 
        // other than -1 then it doesn't need updating 
        if (firstOcc == -1) 
            firstOcc = index; 
  
        // Last occurrence will be updated everytime 
        // the character appears in the array 
        lastOcc = index; 
    
  
class GFG 
  
    // Function to return the maximum 
    // length of the sub-array that
    //  starts and ends with the same element 
    public static int maxLenSubArr(char []arr, int n) 
    
  
        Element []elements = new Element[26]; 
        for (int i = 0; i < n; i++) 
        
            int ch = arr[i] - 'a'
  
            // Initialize the current character 
            // if haven't already 
            if (elements[ch] == null
                elements[ch] = new Element(); 
  
            // Update current character's occurrence 
            elements[ch].updateOccurrence(i); 
        
  
        int maxLen = 0; 
        for (int i = 0; i < 26; i++) 
        
  
            // If current character appears 
            // in the given array 
            if (elements[i] != null)
            
  
                // Length of the longest sub-array that starts 
                // and ends with the same element 
                int len = elements[i].lastOcc - elements[i].firstOcc + 1; 
                maxLen = Math.Max(maxLen, len); 
            
        
  
        // Return the maximum length of 
        // the required sub-array 
        return maxLen; 
    
  
    // Driver code 
    public static void Main() 
    
        char []arr = { 'g', 'e', 'e', 'k', 's' }; 
        int n = arr.Length; 
  
        Console.WriteLine(maxLenSubArr(arr, n)); 
    
  
// This code is contributed by Ryuga

chevron_right


Output:

2


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.



Improved By : rituraj_jain, AnkitRai01