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.

Try It Yourself
redirect icon

[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.

C++
#include <algorithm>
#include <iostream>
#include <string>
using namespace std;

int maxCharGap(string &s)
{
    int n = s.size();
    int res = -1;

    // Check all pairs of indices
    for (int i = 0; i < n; i++)
    {
        for (int j = i + 1; j < n; j++)
        {

            // If same character is found
            if (s[i] == s[j])
            {

                // Update maximum gap
                res = max(res, j - i - 1);
            }
        }
    }

    return res;
}

// Driver code
int main()
{
    string s = "socks";

    cout << maxCharGap(s);

    return 0;
}
C
#include <stdio.h>
#include <string.h>

int maxCharGap(char *s)
{
    int n = strlen(s);
    int res = -1;

    // Check all pairs of indices
    for (int i = 0; i < n; i++)
    {
        for (int j = i + 1; j < n; j++)
        {

            // If same character is found
            if (s[i] == s[j])
            {

                // Update maximum gap
                if (j - i - 1 > res)
                    res = j - i - 1;
            }
        }
    }

    return res;
}

// Driver code
int main()
{
    char s[] = "socks";

    printf("%d", maxCharGap(s));

    return 0;
}
Java
public class GfG {
    static int maxCharGap(String s)
    {
        int n = s.length();
        int res = -1;

        // Check all pairs of indices
        for (int i = 0; i < n; i++) {
            for (int j = i + 1; j < n; j++) {

                // If same character is found
                if (s.charAt(i) == s.charAt(j)) {

                    // Update maximum gap
                    res = Math.max(res, j - i - 1);
                }
            }
        }

        return res;
    }

    // Driver code
    public static void main(String[] args)
    {
        String s = "socks";

        System.out.println(maxCharGap(s));
    }
}
Python
def maxCharGap(s):
    n = len(s)
    res = -1

    # Check all pairs of indices
    for i in range(n):
        for j in range(i + 1, n):

            # If same character is found
            if s[i] == s[j]:

                # Update maximum gap
                res = max(res, j - i - 1)

    return res

# Driver code
if __name__ == "__main__":
    s = "socks"

    print(maxCharGap(s))
C#
using System;

class GfG {
    static int maxCharGap(string s)
    {
        int n = s.Length;
        int res = -1;

        // Check all pairs of indices
        for (int i = 0; i < n; i++) {
            for (int j = i + 1; j < n; j++) {

                // If same character is found
                if (s[i] == s[j]) {

                    // Update maximum gap
                    res = Math.Max(res, j - i - 1);
                }
            }
        }

        return res;
    }

    // Driver code
    static void Main(string[] args)
    {
        string s = "socks";

        Console.WriteLine(maxCharGap(s));
    }
}
JavaScript
function maxCharGap(s)
{
    let n = s.length;
    let res = -1;

    // Check all pairs of indices
    for (let i = 0; i < n; i++) {
        for (let j = i + 1; j < n; j++) {

            // If same character is found
            if (s.charAt(i) === s.charAt(j)) {

                // Update maximum gap
                res = Math.max(res, j - i - 1);
            }
        }
    }

    return res;
}

// Driver code
let s = "socks";

console.log(maxCharGap(s));

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.
C++
#include <algorithm>
#include <iostream>
#include <string>
#include <vector>
using namespace std;

int maxCharGap(string &s)
{

    // first[i] stores the first index of character ('a' + i)
    vector<int> first(26, -1);
    int res = -1;

    for (int i = 0; i < (int)s.size(); i++)
    {
        int ch = s[i] - 'a';

        if (first[ch] == -1)
        {

            // First time seeing this character
            first[ch] = i;
        }
        else
        {

            // Characters between first occurrence and current occurrence
            res = max(res, i - first[ch] - 1);
        }
    }

    return res;
}

// Driver code
int main()
{
    string s = "socks";

    cout << maxCharGap(s);

    return 0;
}
C
#include <stdio.h>
#include <string.h>

int maxCharGap(char *s)
{
    // first[i] stores the first index of character ('a' + i)
    int first[26] = {-1};
    int res = -1;
    int len = strlen(s);

    for (int i = 0; i < len; i++)
    {
        int ch = s[i] - 'a';

        if (first[ch] == -1)
        {
            // First time seeing this character
            first[ch] = i;
        }
        else
        {
            // Characters between first occurrence and current occurrence
            if (i - first[ch] - 1 > res)
                res = i - first[ch] - 1;
        }
    }

    return res;
}

int main()
{
    char s[] = "socks";
    printf("%d", maxCharGap(s));
    return 0;
}
Java
public class GfG {
    public static int maxCharGap(String s)
    {

        // first[i] stores the first index of character ('a'
        // + i)
        int[] first = new int[26];
        for (int i = 0; i < 26; i++) {
            first[i] = -1;
        }
        int res = -1;

        for (int i = 0; i < s.length(); i++) {
            int ch = s.charAt(i) - 'a';

            if (first[ch] == -1) {

                // First time seeing this character
                first[ch] = i;
            }
            else {

                // Characters between first occurrence and
                // current occurrence
                res = Math.max(res, i - first[ch] - 1);
            }
        }

        return res;
    }

    public static void main(String[] args)
    {
        String s = "socks";
        System.out.println(maxCharGap(s));
    }
}
Python
def maxCharGap(s):

    # first[i] stores the first index of character ('a' + i)
    first = [-1] * 26
    res = -1

    for i in range(len(s)):
        ch = ord(s[i]) - ord('a')

        if first[ch] == -1:

            # First time seeing this character
            first[ch] = i
        else:

            # Characters between first occurrence and current occurrence
            res = max(res, i - first[ch] - 1)

    return res


# Driver code
if __name__ == "__main__":
    s = "socks"

    print(maxCharGap(s))
C#
using System;
using System.Linq;

class GfG {
    static int maxCharGap(string s)
    {
        // first[i] stores the first index of character ('a'
        // + i)
        int[] first = new int[26];
        for (int i = 0; i < 26; i++)
            first[i] = -1;
        int res = -1;

        for (int i = 0; i < s.Length; i++) {
            int ch = s[i] - 'a';

            if (first[ch] == -1) {
                // First time seeing this character
                first[ch] = i;
            }
            else {
                // Characters between first occurrence and
                // current occurrence
                res = Math.Max(res, i - first[ch] - 1);
            }
        }

        return res;
    }

    static void Main()
    {
        string s = "socks";

        Console.WriteLine(maxCharGap(s));
    }
}
JavaScript
function maxCharGap(s)
{

    // first[i] stores the first index of character ('a' +
    // i)
    const first = new Array(26).fill(-1);
    let res = -1;

    for (let i = 0; i < s.length; i++) {
        const ch = s.charCodeAt(i) - "a".charCodeAt(0);

        if (first[ch] == -1) {

            // First time seeing this character
            first[ch] = i;
        }
        else {

            // Characters between first occurrence and
            // current occurrence
            res = Math.max(res, i - first[ch] - 1);
        }
    }

    return res;
}

// Driver code
const s = "socks";

console.log(maxCharGap(s));

Output
3

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

Comment