Largest Substring Between Two Equal Characters
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. For example, for 'abca', the substring between the two 'a's is 'bc' with length 2.
This is a state tracking DP problem. Track the first occurrence index of each character using a hash map. When a character appears again, compute the distance between its current index and its first occurrence minus 1 (excluding the characters themselves). Keep the maximum distance seen.
The DP state is the map of first occurrences. Each time we encounter a character already in the map, we compute the span length and update the maximum. If it's a new character, we store its index.
Edge cases include no repeated characters (return -1), overlapping characters where the two equal chars are adjacent (return 0), and multiple repeats of the same character where we need the maximum span.
This problem uses a hash map to store the first occurrence of each character. The state updates when a repeat character is found. This pattern of tracking first/last occurrences is a form of DP where the state is the earliest position of each element.
Example Input & Output
Between the a's: "bc" len=2.
Adjacent a's: len=0.
No repeats.
Between a at 0 and 5: bccb len=4.
No repeated chars.
Algorithm Flow

Solution Approach
Track first occurrence of each char. When seen again, compute length = current - first - 1. Track max.
Time O(n), Space O(n).
Best Answers
import java.util.*;
class Solution {
public int solution(String s) {
Map<Character,Integer> first=new HashMap<>();
int m=-1;
for (int i=0;i<s.length();i++) {
char ch=s.charAt(i);
if (first.containsKey(ch)) {
int len=i-first.get(ch)-1;
if (len>m) m=len;
} else first.put(ch,i);
}
return m;
}
}Comments (0)
Join the Discussion
Share your thoughts, ask questions, or help others with this Challenge.
