Find the longest substring that lies strictly between two equal characters in a string.
You are given a string . Find the maximum length of a substring that is strictly between two equal characters in .
For two equal characters at indices and with , the substring between them is the portion of the string from index to index . Its length is .
Return the largest such length over all pairs of equal characters. If no character appears at least twice, return .
This is a common interview-style string scanning problem: the key is to track where each character was first seen and compare later occurrences efficiently.
Input Format
- A single string
sconsisting of lowercase English letters.
Interpret s as zero-indexed when reasoning about positions.
Output Format
- Return a single integer: the maximum length of a substring between two equal characters, or
-1if no such pair exists.
Constraints
scontains only lowercase English letters- Time complexity should be near linear
Example 1
Input
s = "aa"
Output
0
Explanation
The two equal 'a' characters are adjacent, so the substring between them is empty and has length 0.
Example 2
Input
s = "abca"
Output
2
Explanation
The equal 'a' characters are at indices 0 and 3, so the substring between them is "bc" with length 2.
Show 1 more example
Example 3
Input
s = "cbzxy"
Output
-1
Explanation
No character appears twice, so there is no valid pair of equal characters.
Premium problem context
Unlock deeper context for this problem
Premium adds guided hints, editorial links, similar variants, discussion resources, and concept maps so you can understand why a problem matters, not just solve it once.