Problem Description
Given a string s, determine the length of the longest substring that appears between two identical characters (excluding the two characters). If no such substring exists because no character repeats, return -1.
Key Insights
- Use a data structure (hash table or dictionary) to record the first occurrence of each character.
- As you iterate through the string, whenever you encounter a character that has appeared before, calculate the current substring length (current index - first occurrence index - 1).
- Update the maximum substring length if the current calculation exceeds the previous maximum.
- If no character appears twice, return -1.
Space and Time Complexity
Time Complexity: O(n) – where n is the length of the string; each character is processed once. Space Complexity: O(1) – only a fixed size (26 letters) hash table is used regardless of the string size.
Solution
The approach involves scanning the input string and storing the index of the first occurrence of each character in a hash table. For every character seen later that has already been encountered, compute the length of the substring between its first occurrence and the current index (subtracting 1 to exclude the endpoints). Keep track of the maximum substring length found. If no such pair exists, return -1. This method leverages the properties of hash tables for constant time lookups and updates.