VOOZH about

URL: https://www.geeksforgeeks.org/dsa/maximum-number-characters-two-character-string/

⇱ Maximum Gap Between Two Same Characters in a String - GeeksforGeeks


  • Courses
  • Tutorials
  • Interview Prep

Maximum Gap Between Two Same Characters in a String

Last Updated : 4 Jun, 2026

Given a string s consisting of lowercase English letters, find the maximum number of characters between any two identical characters. If no character repeats, return -1.

Examples:

Input: s = "socks"
Output: 3
Explanation: There are 3 characters between the two occurrences of 's'.

Input: s = "for"
Output: -1
Explanation: No repeating character present.

[Naive Approach] Check Every Pair of Equal Characters - O(n^2) Time O(1) Space

The idea is to check every pair of indices (i, j) where i < j. If s[i] == s[j], then the number of characters between them is j - i - 1. Keep updating the maximum gap found.


Output
3

Time Complexity: O(n^2)
Auxiliary Space: O(1)

[Expected Approach] First Occurrence Tracking - O(n) Time O(1) Space

The idea is to store the first occurrence of each character. While traversing the string, whenever the same character appears again, calculate the gap between the current index and its first occurrence. For any character, the maximum number of characters between two occurrences is obtained using its first occurrence and a later occurrence. Therefore, storing only the first occurrence of each character is sufficient.

Let us understand with example:
Input: s = "socks"

  • Initialize first[26] = {-1} and res = -1.
  • At i = 0, character 's' is seen for the first time, so store its index: first['s'] = 0.
  • At i = 1, 2, 3, characters 'o', 'c', and 'k' are seen for the first time, so store their indices.
  • At i = 4, character 's' is found again. Its first occurrence was at index 0, so gap = 4 - 0 - 1 = 3.
  • Update res = 3 and return it after traversal. Hence, the answer is 3.

Output
3

Time Complexity: O(n)
Auxiliary Space: O(1)

Comment
Article Tags: