find the maximum and minimum occurring character in string
find the maximum and minimum occurring character in string
Start
Declare a string
Declare variables for minimum and maximum occurring characters and assign them to
0.
Use the first for loop to iterate through each character in the string.
Select the characters and initialize their corresponding frequency in the frequency
array to 1.
Use the second for loop to compare the selected character with the rest of the
characters present in the string.
Again use two for loops to iterate over the frequency array.
Use the min and max variable to store the count of minimum and maximum occurring
characters in the string.
Iterate over the loop and compare the count of each character stored in freq with
min and max.
If the count stored in freq is less than the value of min, then store that count in
the min and corresponding character in minChar.
If the count stored in freq is more than the value of max, then store that count in
max and corresponding character in maxChar.
Now, the minChar will store the minimum occurring character and maxChar will store
the maximum occurring character.
Stop
import java.util.*;
public class Main
{
public static void main(String[] args)
{
//Take input from the user
Scanner sc=new Scanner(System.in);
System.out.println("Enter the string: ");
String str=sc.nextLine();
int[] freq = new int[str.length()];
char minChar = str.charAt(0), maxChar = str.charAt(0);
int i, j, min, max;
char string[] = str.toCharArray();
for(i = 0; i < string.length; i++)
{
freq[i] = 1;
for(j = i+1; j < string.length; j++)
{
if(string[i] == string[j] && string[i] != ' ' && string[i] != '0')
{
freq[i]++;
string[j] = '0';
}
}
}
min = max = freq[0];
for(i = 0; i <freq.length; i++)
{
if(min > freq[i] && freq[i] != '0')
{
min = freq[i];
minChar = string[i];
}
if(max < freq[i])
{
max = freq[i];
maxChar = string[i];
}
}
System.out.println("Minimum occurring character: " + minChar);
System.out.println("Maximum occurring character: " + maxChar);
}
}
###################################################################################
#############
A better solution can be achieved using a HashMap to store the frequency of each
character. This way, you can avoid the nested loop and reduce the time complexity
to \(O(n)\).
```java
import java.util.HashMap;
import java.util.Map;
1. Iterating over the string to populate the HashMap takes \( O(n) \) time.
2. Iterating over the HashMap entries to find the min and max frequency characters
also takes \( O(n) \) time.
The space complexity remains \( O(n) \) due to the HashMap used for storing
frequencies.
This approach is more efficient for large strings compared to the previous \
( O(n^2) \) approach. It uses a HashMap to store character frequencies in one pass,
making it easier to find the minimum and maximum frequency characters.