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
For each character that appears at least twice, find the distance between its first and last occurrence. The substring between them excludes the characters themselves, so the length is lastIndex - firstIndex - 1. Track the first occurrence index of each character in a hash map. When a character is seen again, compute the gap and update the maximum.
Only the first occurrence of each character matters because it gives the longest possible gap for that character. Characters appearing only once never update the max.
Time complexity is O(n), space complexity is O(k) where k is alphabet size.
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.
