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
BookshelfApos 0BCBApos 4Distance = 3 booksMemory (Hash Map)First 'A' seen at position 0First 'B' seen at position 1First 'C' seen at position 2โœ“ Max distance: 3
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

n
2n
โœ“ Linear Growth
Space Complexity
O(k)

Where k is the number of unique characters in the string (at most 26 for lowercase letters)

n
2n
โœ“ Linear Space

Constraints

  • 1 โ‰ค s.length โ‰ค 300
  • s contains only lowercase English letters
  • The string may contain duplicate characters
Asked in
Amazon 35 Google 28 Microsoft 22 Meta 18
28.5K Views
Medium Frequency
~12 min Avg. Time
980 Likes
Ln 1, Col 1
Smart Actions
๐Ÿ’ก Explanation
AI Ready
๐Ÿ’ก Suggestion Tab to accept Esc to dismiss
// Output will appear here after running code
Code Editor Closed
Click the red button to reopen