Java | 2 Solution | Brute Force + Optimized
Brute Force\n\npublic int maxLengthBetweenEqualCharacters(String s) {\n        int max = 0;\n        boolean flag = false; \n        for(int i = 0;i<s.length();
**Brute Force**\n```\npublic int maxLengthBetweenEqualCharacters(String s) {\n        int max = 0;\n        boolean flag = false; \n        for(int i = 0;i<s.length();i++){\n            int cm = 0;\n          for(int j = i+1;j<s.length();j++){\n            if(s.charAt(i)==s.charAt(j)){\n                 cm = j - i - 1;\n                 flag = true;\n            }\n          }\n          max = Math.max(max,cm);\n        }\n      if(flag == false) return -1;\n      return max;\n    }\n```\n**Optimized**\n```\nclass Solution {\n    static class Pair{\n          int fo;  //first occurrence\n          int lo;  //last occurrence\n      \n        public Pair(int fo, int lo){\n              this.fo = fo;\n              this.lo = lo;\n        }\n    }\n    public int maxLengthBetweenEqualCharacters(String s) {\n        Pair freq[] = new Pair[26];\n        int max = 0;\n        boolean flag = false;\n        for(int i = 0;i<s.length();i++){\n           char c = s.charAt(i);\n           if(freq[c-\'a\'] != null){\n             freq[c-\'a\'] = new Pair(freq[c-\'a\'].fo,i);\n             flag = true;\n             int size = freq[c-\'a\'].lo - freq[c-\'a\'].fo - 1;\n             max = Math.max(max,size);\n           }\n          else{\n             freq[c-\'a\'] = new Pair(i,i);\n          }\n          \n        }\n      if(flag == false) return -1;\n      return max;\n    }\n}\n```
[]