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. If there is no such substring return -1.

A substring is a contiguous sequence of characters within a string.

Input & Output

Example 1 — Basic Case
$ Input: s = "abaca"
Output: 3
💡 Note: The longest substring between two equal characters is "bac" between the first 'a' (index 0) and last 'a' (index 4), which has length 3.
Example 2 — Multiple Pairs
$ Input: s = "aa"
Output: 0
💡 Note: The two 'a' characters are adjacent with no characters between them, so the substring length is 0.
Example 3 — No Equal Characters
$ Input: s = "cbzxy"
Output: -1
💡 Note: No two equal characters exist in the string, so return -1.

Constraints

  • 1 ≤ s.length ≤ 300
  • s contains only lowercase English letters

Visualization

Tap to expand
Problem Overview: Largest Substring Between Equal CharactersFind the length of longest substring between two equal charactersInput: "abaca"abaca01234a[0] to a[2]: length 1a[2] to a[4]: length 1a[0] to a[4]: length 3 (MAXIMUM)Substring: "bac"Length: 3Output: 3
Understanding the Visualization
1
Input String
Given string with characters at different positions
2
Find Equal Pairs
Identify characters that appear multiple times
3
Calculate Lengths
Measure substring length between equal characters
Key Takeaway
🎯 Key Insight: The maximum substring length for any character is always between its first and last occurrence in the string
Asked in
Amazon 12 Google 8
18.2K Views
Medium Frequency
~15 min Avg. Time
856 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