Skip to main content
Back to problems
Leetcode
Medium
Strings
Hash Maps
Arrays
Largest Substring Between Two Equal Characters

Find the longest substring that lies strictly between two equal characters in a string.

Acceptance 0%
Problem Statement

You are given a string ss. Find the maximum length of a substring that is strictly between two equal characters in ss.

For two equal characters at indices ii and jj with i<ji < j, the substring between them is the portion of the string from index i+1i+1 to index j1j-1. Its length is ji1j - i - 1.

Return the largest such length over all pairs of equal characters. If no character appears at least twice, return 1-1.

This is a common interview-style string scanning problem: the key is to track where each character was first seen and compare later occurrences efficiently.

Input Format

  • A single string s consisting of lowercase English letters.

Interpret s as zero-indexed when reasoning about positions.

Output Format

  • Return a single integer: the maximum length of a substring between two equal characters, or -1 if no such pair exists.

Constraints

  • 1s1051 \le |s| \le 10^5
  • s contains only lowercase English letters
  • Time complexity should be near linear
Examples
Sample cases returned by the problem API.

Example 1

Input

s = "aa"

Output

0

Explanation

The two equal 'a' characters are adjacent, so the substring between them is empty and has length 0.

Example 2

Input

s = "abca"

Output

2

Explanation

The equal 'a' characters are at indices 0 and 3, so the substring between them is "bc" with length 2.

Show 1 more example

Example 3

Input

s = "cbzxy"

Output

-1

Explanation

No character appears twice, so there is no valid pair of equal characters.

Premium problem context

Unlock deeper context for this problem

Premium adds guided hints, editorial links, similar variants, discussion resources, and concept maps so you can understand why a problem matters, not just solve it once.

Guided hints
Editorial and discussion links
Concept map and variants
Sign in to unlock
Track your progress
Sign in to bookmark this problem, save notes, and manage its revision plan.