Largest Substring Between Two Equal Characters Problem
#1624
Try it yourself first
Five languages, sample and hidden tests, right in the browser.
Practice it as an interview
Talk through your solution with an AI interviewer while you code.
Description
LeetCode Problem 1624.
Given a string s, return the length of the longest substring between two equal characters, excluding the two characters. If there is no such substring return -1.
A substring is a contiguous sequence of characters within a string.
Example 1:
Input: s = "aa"
Output: 0
Explanation: The optimal substring here is an empty substring between the two 'a's.
Example 2:
Input: s = "abca"
Output: 2
Explanation: The optimal substring here is "bc".
Example 3:
Input: s = "cbzxy"
Output: -1
Explanation: There are no characters that appear twice in s.
Constraints:
1 <= s.length <= 300scontains only lowercase English letters.
Solution
Approach: Remember Each Character's First Index
For a character that appears several times, the longest substring between two copies uses its first and last occurrences. So we only need each character's first index.
Walk through s. For the character at index i:
- If it has not been seen, record
first[c] = i. - Otherwise, the substring between its first occurrence and
ihas lengthi - first[c] - 1; update the answer with it. Do not overwritefirst[c], so later occurrences still measure from the first one.
Start the answer at -1, which is returned when no character repeats. Two equal neighbours, as in "aa", give length 0, which is a valid answer and different from -1.
Complexity: O(n) time and O(1) extra space (26 letters).
class Solution:
def maxLengthBetweenEqualCharacters(self, s: str) -> int:
first = {} # character -> index of its first occurrence
ans = -1
for i, c in enumerate(s):
if c in first:
ans = max(ans, i - first[c] - 1)
else:
first[c] = i
return ans