Maximum number of characters between any two same character in a string

08 Jul, 2022
Given a string, find the maximum number of characters between any two characters in the string. If no character repeats, print -1. 
Examples:  
Input : str = "abba"
Output : 2
The maximum number of characters are
between two occurrences of 'a'.

Input : str = "baaabcddc"
Output : 3
The maximum number of characters are
between two occurrences of 'b'.

Input : str = "abc"
Output : -1
Approach 1 (Simple): Use two nested loops. The outer loop picks characters from left to right, the inner loop finds the farthest occurrence and keeps track of the maximum. 
C++
Java
Python3
C#
Javascript
// Simple C++ program to find maximum number// of characters between two occurrences of// same character#include <bits/stdc++.h>using namespace std; int maximumChars(string& str){    int n = str.length();    int res = -1;    for (int i = 0; i < n - 1; i++)        for (int j = i + 1; j < n; j++)            if (str[i] == str[j])                res = max(res, abs(j - i - 1));    return res;} // Driver codeint main(){    string str = "abba";    cout << maximumChars(str);    return 0;}
// Simple Java program to find maximum// number of characters between two// occurrences of same characterclass GFG {         static int maximumChars(String str)    {        int n = str.length();        int res = -1;                 for (int i = 0; i < n - 1; i++)            for (int j = i + 1; j < n; j++)                if (str.charAt(i) == str.charAt(j))                    res = Math.max(res,                         Math.abs(j - i - 1));                                  return res;    }         // Driver code    public static void main(String[] args)    {        String str = "abba";                 System.out.println(maximumChars(str));    }} // This code is contributed by vt_m.
# Simple Python3 program to find maximum number# of characters between two occurrences of# same characterdef maximumChars(str):    n = len(str)    res = -1    for i in range(0, n - 1):        for j in range(i + 1, n):            if (str[i] == str[j]):                res = max(res, abs(j - i - 1))    return res # Driver codeif __name__ == '__main__':    str = "abba"    print(maximumChars(str)) # This code is contributed by PrinciRaj1992
// Simple C# program to find maximum// number of characters between two// occurrences of same characterusing System; public class GFG {         static int maximumChars(string str)    {        int n = str.Length;        int res = -1;                 for (int i = 0; i < n - 1; i++)            for (int j = i + 1; j < n; j++)                if (str[i] == str[j])                    res = Math.Max(res,                         Math.Abs(j - i - 1));                                  return res;    }         // Driver code    static public void Main ()    {        string str = "abba";                 Console.WriteLine(maximumChars(str));    }} // This code is contributed by vt_m.
<script>    // Simple Javascript program to find maximum    // number of characters between two    // occurrences of same character         function maximumChars(str)    {        let n = str.length;        let res = -1;                   for (let i = 0; i < n - 1; i++)            for (let j = i + 1; j < n; j++)                if (str[i] == str[j])                    res = Math.max(res,                         Math.abs(j - i - 1));                                    return res;    }         // Driver code    let str = "abba";    document.write(maximumChars(str));      // This code is contributed by unknown2108</script>
Output:  
2
Time Complexity : O(n^2)
Auxiliary Space: O(1)
Approach 2 (Efficient) : Initialize an array”FIRST” of length 26 in which we have to store the first occurrence of an alphabet in the string and another array “LAST” of length 26 in which we will store the last occurrence of the alphabet in the string. Here, index 0 corresponds to alphabet a, 1 for b and so on . After that, we will take the difference between the last and first arrays to find the max difference if they are not at the same position.  
C++
Java
Python3
C#
Javascript
// Efficient C++ program to find maximum number// of characters between two occurrences of// same character#include <bits/stdc++.h>using namespace std; const int MAX_CHAR = 256; int maximumChars(string& str){    int n = str.length();    int res = -1;     // Initialize all indexes as -1.    int firstInd[MAX_CHAR];    for (int i = 0; i < MAX_CHAR; i++)        firstInd[i] = -1;     for (int i = 0; i < n; i++) {        int first_ind = firstInd[str[i]];         // If this is first occurrence        if (first_ind == -1)            firstInd[str[i]] = i;         // Else find distance from previous        // occurrence and update result (if        // required).        else            res = max(res, abs(i - first_ind - 1));    }    return res;} // Driver codeint main(){    string str = "abba";    cout << maximumChars(str);    return 0;}
// Efficient java program to find maximum// number of characters between two// occurrences of same characterimport java.io.*; public class GFG {     static int MAX_CHAR = 256;         static int maximumChars(String str)    {        int n = str.length();        int res = -1;             // Initialize all indexes as -1.        int []firstInd = new int[MAX_CHAR];                 for (int i = 0; i < MAX_CHAR; i++)            firstInd[i] = -1;             for (int i = 0; i < n; i++)        {            int first_ind = firstInd[str.charAt(i)];                 // If this is first occurrence            if (first_ind == -1)                firstInd[str.charAt(i)] = i;                 // Else find distance from previous            // occurrence and update result (if            // required).            else                res = Math.max(res, Math.abs(i                                  - first_ind - 1));        }                 return res;    }         // Driver code         static public void main (String[] args)    {        String str = "abba";                 System.out.println(maximumChars(str));    }} // This code is contributed by vt_m.
# Efficient Python3 program to find maximum# number of characters between two occurrences# of same character MAX_CHAR = 256 def maximumChars(str1):     n = len(str1)    res = -1     # Initialize all indexes as -1.    firstInd = [-1 for i in range(MAX_CHAR)]     for i in range(n):        first_ind = firstInd[ord(str1[i])]         # If this is first occurrence        if (first_ind == -1):            firstInd[ord(str1[i])] = i         # Else find distance from previous        # occurrence and update result (if        # required).        else:            res = max(res, abs(i - first_ind - 1))         return res # Driver codestr1 = "abba"print(maximumChars(str1)) # This code is contributed by Mohit kumar 29
// Efficient C# program to find maximum// number of characters between two// occurrences of same characterusing System; public class GFG {     static int MAX_CHAR = 256;         static int maximumChars(string str)    {        int n = str.Length;        int res = -1;             // Initialize all indexes as -1.        int []firstInd = new int[MAX_CHAR];                 for (int i = 0; i < MAX_CHAR; i++)            firstInd[i] = -1;             for (int i = 0; i < n; i++)        {            int first_ind = firstInd[str[i]];                 // If this is first occurrence            if (first_ind == -1)                firstInd[str[i]] = i;                 // Else find distance from previous            // occurrence and update result (if            // required).            else                res = Math.Max(res, Math.Abs(i                              - first_ind - 1));        }                 return res;    }         // Driver code     static public void Main ()    {        string str = "abba";                 Console.WriteLine(maximumChars(str));    }} // This code is contributed by vt_m.
<script>    // Efficient javascript program to find maximum    // number of characters between two    // occurrences of same character         let MAX_CHAR = 256;         function maximumChars(str)    {        let n = str.length;        let res = -1;               // Initialize all indexes as -1.        let firstInd = new Array(MAX_CHAR);                   for (let i = 0; i < MAX_CHAR; i++)            firstInd[i] = -1;               for (let i = 0; i < n; i++)        {           let first_ind = firstInd[str[i].charCodeAt(0)];                   // If this is first occurrence            if (first_ind == -1)                firstInd[str[i].charCodeAt(0)] = i;                   // Else find distance from previous            // occurrence and update result (if            // required).            else                res = Math.max(res, Math.abs(i                                  - first_ind - 1));        }                   return res;    }         // Driver code    let str = "abba";    document.write(maximumChars(str));      // This code is contributed by patel2127</script>
Output:  
2
Time Complexity : O(n)
Auxiliary Space: O(256)
This article is contributed by Aarti_Rathi and UDIT UPADHYAY. If you like GeeksforGeeks and would like to contribute, you can also write an article using write.geeksforgeeks.org or mail your article to review-team@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above. 
vt_m
princiraj1992
mohit kumar 29
unknown2108
patel2127
codewithrathi
frequency-counting
Zoho
Hash
Strings
Zoho
Hash
Strings
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Given an array A[] and a number x, check for pair in A[] with sum as x (aka Two Sum)
What is Hashing | A Complete Tutorial
Hashing | Set 1 (Introduction)
Internal Working of HashMap in Java
Count pairs with given sum
Write a program to reverse an array or string
Reverse a string in Java
C++ Data Types
Write a program to print all permutations of a given string
Check for Balanced Brackets in an expression (well-formedness) using Stack