✅Beats 100% Users - C++, JAVA, Python, JavaScript || With explanation || 2 Approach
Please Upvote if you find it is helpfull.\n\n---\n\n\n---\n\n# Approach\n Describe your approach to solving the problem. \n\n1. Nested Iteration:\n   - The code
# **Please Upvote if you find it is helpfull.**\n\n---\n![Screenshot 2023-12-31 060743.png](https://assets.leetcode.com/users/images/4661ba3b-1e0d-4d5f-a349-a9660396c502_1703983178.1432881.png)\n\n---\n\n# Approach\n<!-- Describe your approach to solving the problem. -->\n\n**1. Nested Iteration:**\n   - The code uses nested loops to check every possible pair of characters in the string.\n\n**2. Pair Comparison:**\n   - For each pair (left, right), it compares if the characters at those indices are equal.\n\n**3. Longest Distance Calculation:**\n   - If a matching pair is found, it calculates the distance between them (right - left - 1) and updates the maximum length if it\'s larger.\n\n**4. Return Maximum Length:**\n   - The function returns the maximum length found, representing the longest distance between two equal characters.\n\n**Time Complexity:**\n   - O(N^2), where N is the length of the string.\n     - The nested loops iterate through all possible pairs of characters, leading to a quadratic time complexity.\n\n**Space Complexity:**\n   - O(1), constant space.\n     - The code uses a few variables to store temporary values, but its space usage doesn\'t grow with the input string size.\n\n\n# Code\n```C++ []\nclass Solution {\npublic:\n    int maxLengthBetweenEqualCharacters(string s) {\n        int maxDistance = -1;\n\n        // Iterate over all pairs of indices (left, right) in the string.\n        for (int left = 0; left < s.size(); left++) {\n            for (int right = left + 1; right < s.size(); right++) {\n                // Check if characters at indices left and right are equal.\n                if (s[left] == s[right]) {\n                    // Update the maximum distance between equal characters.\n                    maxDistance = max(maxDistance, right - left - 1);\n                }\n            }\n        }\n\n        return maxDistance;\n    }\n};\n\n```\n```java []\nclass Solution {\n    public int maxLengthBetweenEqualCharacters(String s) {\n        int maxDistance = -1;\n\n        for (int left = 0; left < s.length(); left++) {\n            for (int right = left + 1; right < s.length(); right++) {\n                if (s.charAt(left) == s.charAt(right)) {\n                    maxDistance = Math.max(maxDistance, right - left - 1);\n                }\n            }\n        }\n\n        return maxDistance;\n    }\n}\n\n```\n```python []\nclass Solution:\n    def maxLengthBetweenEqualCharacters(self, s: str) -> int:\n        max_distance = -1\n\n        for left in range(len(s)):\n            for right in range(left + 1, len(s)):\n                if s[left] == s[right]:\n                    max_distance = max(max_distance, right - left - 1)\n\n        return max_distance\n\n```\n```javascript []\nclass Solution {\n    maxLengthBetweenEqualCharacters(s) {\n        let maxDistance = -1;\n\n        for (let left = 0; left < s.length; left++) {\n            for (let right = left + 1; right < s.length; right++) {\n                if (s[left] === s[right]) {\n                    maxDistance = Math.max(maxDistance, right - left - 1);\n                }\n            }\n        }\n\n        return maxDistance;\n    }\n}\n\n```\n\n\n\n# Approach\n<!-- Describe your approach to solving the problem. -->\n**1. Character Tracking:**\n   - The code uses a hashmap (`unordered_map` in C++) to track the first occurrence of each character in the string.\n\n**2. Single Pass Iteration:**\n   - It iterates through the string once, efficiently updating the maximum distance as needed.\n\n**3. Key Lookup:**\n   - For each character, it checks if it has already been encountered in the hashmap.\n\n**4. Distance Calculation:**\n   - If a character is found in the hashmap, it calculates the distance between its first occurrence and the current occurrence.\n\n**5. Maximum Distance Update:**\n   - It updates the `maxDiff` variable with the largest distance found so far, representing the longest substring with equal characters at its ends.\n\n**Time Complexity:**\n   - O(N), where N is the length of the string.\n     - The single loop iterates through the string once.\n     - Hashmap lookups have an average-case time complexity of O(1).\n\n**Space Complexity:**\n   - O(C), where C is the number of distinct characters in the string.\n     - The hashmap stores the first occurrence of each character, using space proportional to the number of distinct characters.\n\n\n# Code\n```C++ []\nclass Solution {\npublic:\n    int maxLengthBetweenEqualCharacters(string s) {\n        unordered_map<char, int> charmap;\n        int maxDiff = 0;\n\n        for (unsigned index = 0; index < s.length(); ++index) {\n            char c = s[index];\n\n            unordered_map<char, int>::iterator it = charmap.find(c);\n            if (it != charmap.end()) {\n                int diff = index - it->second;\n                if(maxDiff < diff)\n                    maxDiff = diff;\n                continue;\n                \n            }\n            charmap[c] = index;\n        }\n        return maxDiff - 1;\n    }\n};\n```\n```java []\nimport java.util.HashMap;\n\nclass Solution {\n    public int maxLengthBetweenEqualCharacters(String s) {\n        HashMap<Character, Integer> charMap = new HashMap<>();\n        int maxDiff = 0;\n\n        for (int index = 0; index < s.length(); index++) {\n            char c = s.charAt(index);\n\n            if (charMap.containsKey(c)) {\n                int diff = index - charMap.get(c);\n                maxDiff = Math.max(maxDiff, diff);\n            } else {\n                charMap.put(c, index);\n            }\n        }\n\n        return maxDiff - 1;\n    }\n}\n\n```\n```python []\nclass Solution:\n    def maxLengthBetweenEqualCharacters(self, s: str) -> int:\n        char_map = {}\n        max_diff = 0\n\n        for index, char in enumerate(s):\n            if char in char_map:\n                diff = index - char_map[char]\n                max_diff = max(max_diff, diff)\n            else:\n                char_map[char] = index\n\n        return max_diff - 1\n\n```\n```javascript []\nclass Solution {\n    maxLengthBetweenEqualCharacters(s) {\n        const charMap = {};\n        let maxDiff = 0;\n\n        for (let index = 0; index < s.length; index++) {\n            const c = s[index];\n\n            if (charMap[c]) {\n                const diff = index - charMap[c];\n                maxDiff = Math.max(maxDiff, diff);\n            } else {\n                charMap[c] = index;\n            }\n        }\n\n        return maxDiff - 1;\n    }\n}\n\n```\n\n---\n\n![imgleetcode.png](https://assets.leetcode.com/users/images/cc4dcff5-83eb-4935-9f9f-f06f4d1d5197_1703983212.9701.png)\n\n---\n\n\n
['Hash Table', 'String', 'Python', 'C++', 'Java', 'JavaScript']