Coding Challenge Day-7: Problem 2: Find character(s) with maximum recurrence in a string

Hello! So I’m doing a 30 day coding challenge where I solve around 3-5 questions per day and thought of posting them here on my blog so that you guys can join the challenge too!

Welcome to Coding challenge Day 7: Problem 2! Be sure to post your answers, queries etc in the comments!

Problem: Find character(s) with maximum recurrence in a string

Sample input: “Today is Monday”
Output: The maximum recurring character(s) in string Today is Monday is a d o y which occur 2 times

Sample input: “Coding Challenge”
Output: The maximum recurring character(s) in string Coding Challenge is C e g l n which occur 2 times

Solution:

  • convert string to character array
  • take an integer array ‘index’ of length 256 to stor the number of times a character occurs
  • run loop1 to initialize all elements of ‘index’ to zero
  • run loop2 to increase value of those indices which have same value as ASCII value of the characters in string
  • run loop3 to find max times a character is repeated
  • run loop4 to print those character values which recur max times
package string;

public class P {
	
	public static void main (String [] args){
		String str= "Today is Monday";
		int length= str.length();
		char [] c= str.toCharArray();
		int [] index= new int [256];
		//loop1
		for(int i=0; i<256; i++){
			index[i]=0;
		}
		//loop2
		for(int i=0; i<length; i++){
			if(c[i]!=' '){
			 int convert= c[i];
			 index[convert]++;
			}
		}
		
		int max=0;
		//to find max
		for(int i=0; i<256; i++){
			if(index[i]>max)
				max=index[i];
		}
		
	  System.out.print("The maximum recurring character(s) in string " + str+ " is ");
		for (int i=0; i<256; i++){
			if (index[i]==max)
				
				System.out.print((char)i+ " ");
		}
		
		System.out.println("which occur " + max+ " times");
		
	}

}

Download Code

Happy Learning !!

Leave a Reply

PHP JS HTML CSS BASH PYTHON CODE

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.

%d bloggers like this:
search previous next tag category expand menu location phone mail time cart zoom edit close