One Pass HashMap Solution and O(1) Space Solution
We can use a HashMap (or an array, but it is the same idea behind) to store the first time occurence index. \nIf we meet the same character again, we can calcul
We can use a HashMap (or an array, but it is the same idea behind) to store the **first time** occurence index. \nIf we meet the same character again, we can calculate the length and compare to the final result. That is it! :)\n\n**Solution 1: *O(n)* time and *O(n)* space complexity**\n```\n    public int maxLengthBetweenEqualCharacters(String s) {\n        int res = -1;\n        char[] ch = s.toCharArray();\n        HashMap<Character, Integer> map = new HashMap<>();\n        for (int i=0 ; i<s.length(); i++) {\n            if (map.containsKey(ch[i])) {\n                res = Math.max(res, i - 1 - map.get(ch[i]));\n            } else {\n                map.put(ch[i], i);\n            }\n        }\n        return res;\n    }\n```\n\n**Solution 2 (inspired by pgmreddy): O(n^2) time and *O(1)* space complexity**\n```\n    public int maxLengthBetweenEqualCharacters(String s) {        \n        int res = -1;   \n        int len = s.length();\n        for (int i=0; i<len; i++){\n            char c = s.charAt(i);\n            int firstPos = s.indexOf(c); // The time complexity of indexOf() is O(n)!\n            int lastPos = s.lastIndexOf(c); // The time complexity of lastIndexOf() is O(n)!\n            res = Math.max(res, lastPos - firstPos - 1);\n        }   \n        return res; \n    }\n```
[]