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
Largest Substring Between Two Equal Characters INPUT String s = "abaca" a idx 0 b idx 1 a idx 2 c idx 3 a idx 4 Equal Characters: 'a' appears at indices 0, 2, 4 Hash Map Structure char --> first_index 'a' --> 0 'b' --> 1 'c' --> 3 ALGORITHM STEPS 1 Initialize Create map, result = -1 2 Iterate String For each character at i 3 Check Map If char exists: calc distance Else: store first position 4 Update Result result = max(result, i-first-1) Trace: i=0: 'a' new, map[a]=0 i=1: 'b' new, map[b]=1 i=2: 'a' found! 2-0-1=1 i=4: 'a' found! 4-0-1=3 FINAL RESULT Longest substring found: a b a c a "bac" (length 3) Output: 3 OK - Verified! Between 'a' at 0 and 4 First 'a': index 0 Last 'a': index 4 Length: 4 - 0 - 1 = 3 Key Insight: Store only the FIRST occurrence of each character in the hash map. When we encounter a character again, calculate: current_index - first_index - 1. This gives the substring length BETWEEN them. By keeping only the first position, we maximize the distance when the same character appears later. TutorialsPoint - Largest Substring Between Two Equal Characters | Hash Map Approach
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