Table of Contents

In Java, we can find the lowest frequency character in a string using either ASCII values or Maps from the Collection framework.

If the input string is “add”, then ‘a’ is the least occurred character in the given string “add”.

In this article we will learn to finding lowest repeated character in a string through an example, detailed logic and program explanation for better understanding.

Required Knowledge

  • Java programming basics
  • Java operators
  • ASCII values
  • Maps (Collection frameworks)
  • Loop concepts
  • Conditional statements

Problem Statement

We need to develop a Java program to find the lowest frequency character in a string. The program should take an input string and identify the character with the lowest frequency. If there are multiple characters with the same lowest frequency, it should select the one that comes first in alphabetical order. Let’s see an example,

Example:

For a given input String str “Java”, Output should be “J”.

Explanation:

Input String str: Java

Character frequencies:
'J': 1
'a': 2
'v': 1

Repeated characters: 'a' (appears 2 times)

Non-repeated characters: 'J', 'v' (each appears 1 time)

First Character in Alphabetical Order (among the lowest frequency characters): 'J'

Hence, the lowest frequency character is 'J'.

Logic to find lowest frequency character in a string

There are multiple logics to find the lowest frequency character in a string in java programming language.

Logic 1: Using ASCII value

  • To find lowest frequency of a character using ASCII value, first step is to create a method which takes string as input.
  • Using string.replace(“\\s+”, “”).toLowercase() method remove all white spaces and convert string into lowercase text. (\\s might be a whitespaces, tabs or line breaks and + indicates one or more occurrences of whitespace characters).
  • Using if statement, checks if the processed string is empty and returns a null character if true.
  • Create an array countArray of size 256 to hold the frequency count of each ASCII character.
  • It iterates through the characters of the string and increments the corresponding index in the countArray for each character using for loop.
  • Initialize two variables, minFrequencyCharacter to store the character with the lowest frequency and minOccurrence to store the minimum frequency found.
  • Using for loop, programs iterates over countArray to find the character with the lowest non-zero frequency:
    • Using if statement, If a character’s frequency is greater than 0 and less than minOccurrence, it updates minOccurrence with this frequency and minFrequencyCharacter with the corresponding character.
    • It returns minFrequencyCharacter and this method is called from the main method to display the result.

Logic 2: Using Maps

  • To count lowest frequency of a character in a string, we will begin by create a method with input string. Remove all whitespace from string.
  • Converts the resulting string to uppercase.
  • Initialize a HashMap (countMap) to store character-frequency pairs.
  • Using for loop, iterates through each character in the string and updates the count of each character in the map.
  • Initializes variables to track the minimum frequency and its corresponding character.
  • Use another for loop to iterate through the countMap, Inside the loop, comparing frequencies to find the character with the lowest frequency using if statement.
  • Returns the character with the lowest frequency found and call this method in the main and get the result.

Java program to find the lowest frequency character in a string

Program 1: Using ASCII value

In the below program we are using ASCII value to find the lowest frequency character in a string.

import java.util.Scanner;
public class LowestOccurredChar2 {
	public static void main(String[] args) {
		Scanner sc = new Scanner(System.in);
		System.out.println("Enter a text");
		String str = sc.nextLine();
		char lowestFrequencyChar = lowestOccurredCharacter(str);
		System.out.println("Lowest Occurred character: " + lowestFrequencyChar);
		sc.close();
	}
	public static char lowestOccurredCharacter(String string) {
		string =string.replaceAll("\\s+", "").toLowerCase();
		if (string.isEmpty()) {
            return '\0';
        }
		int[] countArray = new int[256];
		for (char ch: string.toCharArray()) {
			countArray[ch]++;
		}
		char minFrequencyCharacter = '\0';
		int minOccurrence = Integer.MAX_VALUE;;
		for (int i = 0; i < countArray.length; i++) {
			if (countArray[i] > 0 && countArray[i] < minOccurrence) {
                minOccurrence = countArray[i];
                minFrequencyCharacter = (char) i;
            }
		}
		return minFrequencyCharacter;
	}
}

Output:

Enter a text
Welcome to Interview Expert
Lowest Occurred character: c

Java program explanation to find the lowest frequency character in a string

  • This java program reads a text input from the user and processes it to remove spaces and convert it to lowercase.
  • Checks if the processed string is empty and returns a null character if true.
  • Uses an array of size 256 to count the frequency of each ASCII character in the string.
  • Iterates through the string to update the frequency count in the array.
  • Finds the character with the lowest non-zero frequency by iterating through the frequency array.
  • Prints the character with the lowest frequency. If multiple characters have the same frequency, the alphabetically first one is chosen.

Program 2: Using Maps

In the below program we are using Maps to find the lowest frequency character in a string.

import java.util.HashMap;
import java.util.Map;
import java.util.Scanner;
public class LowestOccurredChar {
	public static void main(String[] args) {
		Scanner sc = new Scanner(System.in);
		System.out.println("Enter a text");
		String str = sc.nextLine();
		char lowestFrequencyChar = lowestRepeatedChar(str);
		System.out.println("Lowest Occurred character: " + lowestFrequencyChar);
		sc.close();
	}
	public static char lowestRepeatedChar(String string) {
		string = string.replaceAll("\\s+", "").toUpperCase();
		Map<Character, Integer> countMap = new HashMap<>();
		for (char character : string.toCharArray()) {
			countMap.put(character, countMap.getOrDefault(character, 0) + 1);
		}
		int minFrequency = Integer.MAX_VALUE; ;
		char minFrequencyChar = '\0';
		for (Map.Entry<Character, Integer> entry : countMap.entrySet()) {
			if (entry.getValue() < minFrequency) {
	             minFrequency = entry.getValue();
	             minFrequencyChar = entry.getKey();
	         }
		}	 
		return minFrequencyChar;
	}
}

Output:

Enter a text
Java Programming Language
Lowest Occurred character: E

Java program explanation to find the lowest frequency character in a string

  • The program asks the user to enter a text input.
  • It removes all whitespace characters from the input string and converts it to uppercase for uniformity.
  • Using a HashMap, it counts the frequency of each character in the input string.
  • It iterates through each character of the input string and updates the count of each character in the map.
  • After counting the frequencies, it iterates through the map entries to find the character with the lowest frequency.
  • It returns the character with the lowest frequency found in the input string.

Conclusion

The java programs we developed here will find the lowest frequency character in a string using ASCII value and Maps.

How useful was this post?

Click on a star to rate it!

Average rating 0 / 5. Vote count: 0

No votes so far! Be the first to rate this post.

Categorized in:

Java Coding,