Largest Substring Between Two Equal Characters - Problem
Given a string s, return the length of the longest substring between two equal characters, excluding the two characters themselves. If no such substring exists, return -1.
A substring is a contiguous sequence of characters within a string.
Example: In the string "abca", the characters 'a' appear at indices 0 and 3. The substring between them is "bc" with length 2.
Your task is to find the maximum possible length among all such substrings formed by pairs of equal characters.
Input & Output
example_1.py โ Basic Case
$
Input:
s = "abca"
โบ
Output:
2
๐ก Note:
The characters 'a' appear at indices 0 and 3. The substring between them is "bc" with length 2.
example_2.py โ Multiple Pairs
$
Input:
s = "cbzxy"
โบ
Output:
-1
๐ก Note:
No two equal characters exist in the string, so return -1.
example_3.py โ Adjacent Characters
$
Input:
s = "aa"
โบ
Output:
0
๐ก Note:
The characters 'a' appear at indices 0 and 1. The substring between them is empty with length 0.
Visualization
Tap to expand
Understanding the Visualization
1
Walk along the shelf
Process each character position one by one
2
Remember first bookends
Store the first position where each character appears
3
Measure distances
When we see a character again, calculate the distance from its first occurrence
4
Track maximum
Keep the longest distance found so far
Key Takeaway
๐ฏ Key Insight: We only need to remember the first occurrence of each character. Any subsequent occurrence will give us a valid substring, and later occurrences naturally provide longer distances.
Time & Space Complexity
Time Complexity
O(n)
Single pass through the string, hash map operations are O(1) average case
โ Linear Growth
Space Complexity
O(k)
Where k is the number of unique characters in the string (at most 26 for lowercase letters)
โ Linear Space
Constraints
- 1 โค s.length โค 300
- s contains only lowercase English letters
- The string may contain duplicate characters
๐ก
Explanation
AI Ready
๐ก Suggestion
Tab
to accept
Esc
to dismiss
// Output will appear here after running code