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

CServer Side ProgrammingProgramming

We are given a string of alphabets. The array can have at least two occurrences of the same character. The task here is to find the maximum number of characters between any two occurrences of a character. If there is no repetition of any character then return -1.

Input − string str = “abcdba”

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

Explanation − The repeating characters are ‘a’ and ‘b’ only with indexes −

1. 2‘a’ first index 0 last 5 , characters in between 5-0-1=4
2. ‘b’ first index 1 last 4 , characters in between 4-1-1=2
   Maximum character in between repeating alphabets : 4

Input − string str = “AbcAaBcbC”

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

Explanation − The repeating characters are ‘A’ , ‘b’ , ‘c’ only with indexes −

1. ‘A’ first index 0 last 3 , characters in between 3-0-1=2
2. ‘b’ first index 1 last 7 , characters in between 7-1-1=5
3. ‘c’ first index 2 last 6 , characters in between 6-2-1=3
   Maximum character in between repeating alphabets : 5

Note − if the input string is “abcdefg” , there are no repeating characters so the function will return -1.

Approach used in the below program is as follows

  • We take a character array having a string of characters as Str[]

  • The function maxChars( char str[],int n) is used to calculate the maximum number of characters between any two repeating alphabets.

  • We initialize the variable maxC with -1.

  • Inside for loop traverse the array of string from the beginning.

  • In nested for loop traverse the remaining characters and search for repetitions if any. ( if ( str[i] == str[j] ).

  • If it is true then calculate difference between characters by subtracting the indexes. ( temp=j-i-1)

  • If this value is maximum found so far, then store it in maxC.

  • Return maxC after traversing the whole string.

Example

 Live Demo

#include <stdio.h>
#include <stdio.h>
#include <math.h>
int maxChars(char str[],int n){
   int size = n;
   int maxC = -1;
   for (int i = 0; i < n - 1; i++)
      for (int j = i + 1; j < n; j++)
         if (str[i] == str[j]){
            int temp=abs(j-i-1);
            maxC = maxC>temp?maxC:temp;
         }
   return maxC;
}
// Driver code
int main(){
   char Str[] = "AbcAaBcbC";
   printf("Maximum number of characters between any two same character in a string :%d",
   maxChars(Str,9) );
   return 0;
}

Output

If we run the above code it will generate the following output −

Maximum number of characters between any two same character in a string : 5
raja
Published on 14-Aug-2020 08:02:17
Advertisements