Largest Substring Between Two Equal Characters — LeetCode 1624 Python Solution

EasyHash TableString
Problem
#1624
Pattern
Hash Map
Reading time
2 min

The problem

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.

Example

Input
s = "aa"
Output
0
Explanation
The optimal substring here is an empty substring between the two 'a's.

Python solution

Python
class Solution:
    def maxLengthBetweenEqualCharacters(self, s: str) -> int:
        d = {}
        ans = -1
        for i, c in enumerate(s):
            if c in d:
                ans = max(ans, i - d[c] - 1)
            else:
                d[c] = i
        return ans

Complexity

MeasureComplexity
TimeO(n)
SpaceO(n) auxiliary

Pattern: Hash Map

Trade memory for time: remember what you have seen so the second pass never happens. LeetCode 1624. Largest Substring Between Two Equal Characters is filed here on both counts: the reference solution below belongs to the algorithm family this hub collects, and LeetCode tags it Hash Table.

The hash map guide has the Python template for the pattern and the 709 LeetCode problems that use it.

Related problems

Frequently asked questions

How hard is LeetCode 1624. Largest Substring Between Two Equal Characters?
LeetCode 1624. Largest Substring Between Two Equal Characters is rated Easy on LeetCode.
What is the time complexity of LeetCode 1624. Largest Substring Between Two Equal Characters?
The Python solution on this page runs in O(n).
What is the space complexity of LeetCode 1624. Largest Substring Between Two Equal Characters?
The Python solution on this page uses O(n) auxiliary space.
What topics does LeetCode 1624. Largest Substring Between Two Equal Characters cover?
LeetCode 1624. Largest Substring Between Two Equal Characters is tagged Hash Table and String on LeetCode.

Stuck on problems like this in a live interview?

Stealth Interview is a desktop app for macOS and Windows. It reads the problem off your screen and returns a working solution with a step-by-step explanation and its time and space complexity — invisible to screen sharing.

Get Stealth Interview