Problem 1624

Abstract / Summary

Find the longest distance between two same letters in a string.

Note

The full problem description, including helpful examples, can be found on LeetCode.

Python 1624.py

class Solution:
    def maxLengthBetweenEqualCharacters(self, s: str) -> int:
        first = defaultdict(int)
        last  = defaultdict(int)
        for i, c in enumerate(s):
            if c not in first:
                first[c] = i
            last[c] = i

        result = -1
        for l in last:
            distance = last[l] - first[l]
            if distance > 0:
                result = max(result, distance - 1)
        return result
15 lines | 465 bytes | submitted December 31, 2023 | GitHub   tab size 4 | low complexity

Difficulty

This problem is ranked as
easy medium hard

and has an acceptance rate of about 68% (200k+ submissions).

Typical patterns to solve this problem:
  • Hash Table
  • String
I solved 663 easy, 1250 medium and 309 hard problems

AI Disclaimer

Every single line of code was written by me, 100% from scratch, between August 2023 and August 2024.
However, two years later I set up this website and used various AI tools to generate most of the walkthrough / explanations below.

See this dedicated page for more details.
LeetCode profile | GitHub repo

Code Walkthrough

Overview

The provided implementation solves the problem of finding the longest substring that lies strictly between two identical characters in a given string. It does this by recording the earliest and latest index of each character, then computing the maximum gap between those indices, subtracting one to exclude the bounding characters themselves. The function returns -1 when no such pair exists.

First Pass - Recording First and Last Occurrences

The algorithm begins by iterating over the input string once. During this traversal it populates two dictionaries: one that stores the first index at which each character appears, and another that stores the most recent index seen for each character. The use of defaultdict(int) ensures that any missing key defaults to 0, but the code explicitly checks for the presence of a character before assigning its first occurrence.

first = defaultdict(int)
last  = defaultdict(int)
for i, c in enumerate(s):
    if c not in first:
        first[c] = i
    last[c] = i

Because the loop processes characters in order, the first time a character is encountered its index is captured in first. Every iteration updates last, guaranteeing that after the loop last[c] holds the greatest index where c appears.

Second Pass - Determining the Maximum Gap

After the initial scan, the algorithm examines each character that has a recorded last position. For each character it computes the distance between its last and first indices. A positive distance indicates that the character appears at least twice. The result is updated with the largest distance minus one, which corresponds to the length of the substring strictly between the two equal characters.

result = -1
for l in last:
    distance = last[l] - first[l]
    if distance > 0:
        result = max(result, distance - 1)
return result

The subtraction of one removes the two bounding characters from the count, as required by the problem statement.

Edge Cases Handled

When the input string contains a character only once, the computed distance is zero, and the conditional if distance > 0 prevents it from influencing the result. Consequently, strings with all unique characters correctly yield -1.

If the string is empty, the initial loop does not execute, leaving both dictionaries empty. The subsequent iteration over last is a no-op, and the function returns the initial value -1, which aligns with the expectation that no pair of equal characters exists.

When a character appears multiple times, the algorithm automatically selects the outermost pair because first stores the earliest index and last stores the latest index. This ensures the longest possible substring for that character is considered.

Performance Optimizations

The solution achieves its goal with two linear passes over the data. The first pass records both first and last positions in a single traversal, avoiding the need for separate scans for each dictionary. This reduces the total number of element accesses.

Using dictionaries keyed by characters provides constant-time lookups for both first and last. The check if c not in first prevents unnecessary overwriting of the first occurrence, which would otherwise require a conditional assignment each iteration.

The final aggregation loop iterates only over the keys present in last, which is at most the number of distinct characters in the string. This bound is typically far smaller than the length of the string, especially for inputs with repeated characters, further limiting the work performed in the second phase.

Overall, the algorithm balances simplicity with efficient use of data structures, delivering a solution that scales linearly with the size of the input while keeping auxiliary storage proportional to the alphabet size.

written by openai gpt

ELI5 - Simplified Explanation

Imagine a long train made of colored blocks where each block has a letter on it. This code is like a game played to find the two blocks that have the same letter on them and are as far apart as possible.

First, the code walks down the train from the front to the back. It carries two notebooks. In the first notebook, it writes down where it sees each letter for the very first time. In the second notebook, it keeps updating the spot where it last sees that same letter.

Once it has checked every single block, it starts looking through what it wrote down. It picks a letter and looks at its first spot and its last spot. To find how many empty spaces are between them, it subtracts the first spot number from the last spot number and then takes away one more.

It does this for every different letter it found. If it finds a distance that is bigger than any other distance it has seen before, it saves that number to remember it. Finally, it tells you the biggest gap it discovered between any two matching letters.

written by google gemini

Code Quality

Several LLMs ranked my code quality on a scale from 1 (very poor) to 10 (outstanding):
n = 27 | median = 8 | μ = 7.44 | σ = 1.07

Complexity Analysis

Time: linear
As a rule of thumb, the maximum input size for one second execution time is
  • factorial: up to 10 elements
  • exponential: up to 20 elements
  • polynomial: a few thousand elements
  • loglinear: up to 100,000 elements
  • linear: a few million elements
  • logarithmic: a billion elements
  • constant: practically unlimited
generated automatically

Other Solutions

I wrote a basic crawler to find other solutions to that problem.
Obviously, I did that after I solved the problem myself.

In general, AlgoMonster and WalkCCC solutions are high-quality and always worth a look.
I haven't checked most of the other solutions, but they might be helpful as well.

And of course, the LeetCode forum is always a good place (or even the best) to look for alternative approaches.

(click on a column header to sort the table)
author
author solutions
www AlgoMonster C++ Python Java TS
WalkCCC C++ Python Java
leetcode.ca C++ Python Java Go C Rust TS
Progiez C++ Python Java
github black-shadows C++
charles-wangkai Java
DimitrisJim C
everthis JS
fartem Ruby
fsq C++
halfrost Go
haoel C++
JoshCrozier JS
keineahnung2345 C++
Krazune C++
lkwq007 Python
muhammadfarhankt Go
pruthvikp Python
suxrobGM C#
trung-hn Python
varunu28 Java
YuriSpiridonov Python
AlgoMonster C++, Python, Java, TypeScript
WalkCCC C++, Python, Java
leetcode.ca C, C++, Go, Java, Python, Rust, TypeScript
Progiez C++, Java, Python
black-shadows C++, C++
charles-wangkai Java
DimitrisJim C
everthis JavaScript
fartem Ruby
fsq C++
halfrost Go
haoel C++
JoshCrozier JavaScript
keineahnung2345 C++
Krazune C++
lkwq007 Python
muhammadfarhankt Go
pruthvikp Python
suxrobGM C#
trung-hn Python
varunu28 Java
YuriSpiridonov Python
35 links | 22 authors | 10 languages

Videos

5 videos   did my crawler come up with invalid videos ? drop me a line.

Solved On The Same Day

5 solutions   December 31, 2023

Extra

There are a few extra pages giving you some insights into my setup:
  • Tech Stack - my development environment and tools
  • AI - how AI helped me create this website (NOT solving the problems)
  • Progress - progression over time
  • Quality - code quality