Simple Solution Using Character Array
Intuition\nWe\'ve to find largest substring between two equal characters. So we can find length of substring between first and last occurence of each alphabet a
# Intuition\nWe\'ve to find largest substring between two equal characters. So we can find length of substring between first and last occurence of each alphabet and return the maximum one as the answer.\n\n# Approach\nWe can intialize arrays **first** for storing first occurence of character and **last** for storing last occurence of character in given string and arrays will be of size 26 each where each index gives occurence index for each alphabet.\nWe can find index as char - \'a\' so that \'0\' will be index for occurence of a, \'1\' will be for b and so on. We are intializing both the arrays with -1 as \'0\' can be index for any of the element.\n\nIn first array we have to store the minimum index at which given element is occuring. So we calculate required index that is current as curr = s[i] - \'a\'. If first[curr] == -1 i.e we\'ve not found any occurence yet so we can store the current index as least occurence otherwise we\'ll set the min(first[curr], i) as occurence.\nLikewise for last index we\'ve to store maximum index.\n\nWe\'ll initialize ans with INT_MIN\nSuppose first[i] gives the index of first occurence of a character and last[i] gives the last index of occurence of character so the lenght of substring between the two characters will be **ans = max(ans, **(last[i] - first[i] - 1)**)**. Just we need to check if value at respective index in both the arrays is not equal to -1 and not equal to each other as in this case there will be only one occurence which is contradictory to our problem.\n\nAt the end if ans == INT_MIN means we\'ve not found any substring satisfying given condition so we\'ll return -1 otherwise we can return the ans.\n\n# Complexity\n- Time complexity: O(n) as we\'re traversing loop only once\n\n- Space complexity: O(1) as we\'re using only char arrays and some variables which are independent of size of input\n\n# Code\n```\nclass Solution {\npublic:\n    int maxLengthBetweenEqualCharacters(string s) {\n        int first[26], last[26];\n        memset(first, -1, sizeof(first));\n        memset(last, -1, sizeof(last));\n        for(int i = 0; i < s.length(); i++)\n        {\n            int curr = s[i] - \'a\';\n            first[curr] = first[curr] != -1 ? min(first[curr], i) : i;\n            last[curr] = last[curr] != -1 ? max(last[curr], i) : i;\n        }\n        int ans = INT_MIN;\n        for(int i = 0; i < 26; i++)\n        {\n            if(first[i] != -1 && last[i] != -1 && first[i] != last[i])\n            {\n                ans = max(ans, last[i] - first[i] - 1);\n            }\n        }\n        return ans == INT_MIN ? -1 : ans;\n    }\n};\n```
['String', 'C++']