Largest Substring Between Two Equal Characters

To solve this problem, we can use a hash map to store the first occurrence of each character in the string. For each subsequent occurrence of the character, we calculate the distance from the first occurrence to the current position, and keep track of the maximum such distance. This maximum distance is the length of the longest substring between two equal characters.

Let’s implement this in Python:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
class Solution:
    def maxLengthBetweenEqualCharacters(self, s: str) -> int:
        char_index_map = {}
        max_length = -1

        for i in range(len(s)):
            if s[i] in char_index_map:
                max_length = max(max_length, i - char_index_map[s[i]] - 1)
            else:
                char_index_map[s[i]] = i

        return max_length

We iterate through the string. If a character is already in the hash map, we calculate the distance from its first occurrence to the current position and update the maximum length if necessary. If the character is not in the hash map, we add it to the map with its current position. Finally, we return the maximum length.

The time complexity of this solution is O(n), where n is the length of the string, because we perform a single pass through the string. The space complexity is O(n), because in the worst case, we need to store every character in the string in the hash map.