Code Logo

Largest Substring Between Two Equal Characters

Published at24 Jul 2026
Easy 0 views
Like0

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

Example 1
Input
"abca"
Output
2
Explanation

Between the a's: "bc" len=2.

Example 2
Input
"aa"
Output
0
Explanation

Adjacent a's: len=0.

Example 3
Input
"cbzxy"
Output
-1
Explanation

No repeats.

Example 4
Input
"abccba"
Output
4
Explanation

Between a at 0 and 5: bccb len=4.

Example 5
Input
"abc"
Output
-1
Explanation

No repeated chars.

Algorithm Flow

Recommendation Algorithm Flow for Largest Substring Between Two Equal Characters
Recommendation Algorithm Flow for Largest Substring Between Two Equal Characters

Solution Approach

Track first occurrence of each char. When seen again, compute length = current - first - 1. Track max.

function solution(s) {
  var first = {};
  var maxLen = -1;
  for (var i = 0; i < s.length; i++) {
    var ch = s.charAt(i);
    if (first[ch] !== undefined) {
      var len = i - first[ch] - 1;
      if (len > maxLen) maxLen = len;
    } else {
      first[ch] = i;
    }
  }
  return maxLen;
}

Time O(n), Space O(n).

Best Answers

java
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;
    }
}