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:Â
Â
C++
// C++ implementation of the approach#include <bits/stdc++.h>using namespace std;Â
// Class that represents a single element// of the given array and stores it's first// and the last occurrence in the arrayclass Element{public:Â Â Â Â int firstOcc, lastOcc;Â Â Â Â Element();Â Â Â Â void updateOccurence(int);};Â
Element::Element(){Â Â Â Â firstOcc = lastOcc = -1;}Â
// Function to update the occurrence// of a particular character in the arrayvoid Element::updateOccurence(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;}Â
// Function to return the maximum length of the// sub-array that starts and ends with the same elementint maxLenSubArr(string arr, int n){Â Â Â Â Element elements[26];Â
    for (int i = 0; i < n; i++)    {        int ch = arr[i] - 'a';Â
        // Update current character's occurrence        elements[ch].updateOccurence(i);    }Â
    int maxLen = 0;    for (int i = 0; i < 26; i++)    {        // Length of the longest sub-array that starts        // and ends with the same element        int len = elements[i].lastOcc -                   elements[i].firstOcc + 1;        maxLen = max(maxLen, len);    }Â
    // Return the maximum length of    // the required sub-array    return maxLen;}Â
// Driver Codeint main(){Â Â Â Â string arr = "zambiatek";Â Â Â Â int n = arr.length();Â
    cout << maxLenSubArr(arr, n) << endl;Â
    return 0;}Â
// This code is contributed by// sanjeev2552 |
Java
// 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 arrayclass 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));    }} |
Python3
# 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 |
C#
// 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 |
Javascript
<script>Â
// Javascript 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{Â Â Â Â Â Â Â constructor()Â Â Â Â {Â Â Â Â Â Â Â Â this.firstOcc = -1;Â Â Â Â Â Â Â Â this.lastOcc = -1;Â Â Â Â }Â
    // Function to update the occurrence     //of a particular character in the array     updateOccurrence(index){ Â
        // If first occurrence is set to         //something other than -1 then it        //doesn't need updating         if (this.firstOcc == -1)            this.firstOcc = index;Â
        // Last occurrence will be updated         // everytime the character appears        // in the array         this.lastOcc = index;         }}    // Function to return the maximum length // of the sub-array that starts and ends// with the same element function maxLenSubArr(arr, n){   let elements = new Array(26);       for(let i=0;i<26;i++)   {       elements[i] = new Element();   }Â
    for(let i=0;i<n;i++)       {           let ch = arr[i].charCodeAt(0) - 'a'.charCodeAt(0);Â
        // Update current character's occurrence         elements[ch].updateOccurrence(i);        }    let maxLen = 0;    for(let i=0;i<26;i++)    {        // Length of the longest sub-array that starts        // and ends with the same element        let 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 Â
let arr = "zambiatek";let n = arr.length;Â
console.log(maxLenSubArr(arr, n));Â
// This code is contributed by akashish__Â
</script> |
2
Â
Time Complexity: O(N)Â
Auxiliary Space: O(N)
Related Topic: Subarrays, Subsequences, and Subsets in Array
Ready to dive in? Explore our Free Demo Content and join our DSA course, trusted by over 100,000 zambiatek!



