Check If a String is Heterogram in Java



A heterogram is a string where each letter appears only once, with no repeated characters. This property makes it unique and an interesting problem to solve in Java. In this article, we will learn to determine whether a given string is a heterogram using a frequency-based approach and introduce an alternative using a Set.

Set

A Set is a type of Collection designed to hold unique elements, ensuring no duplicates are present. It reflects the concept of a mathematical set and includes methods from the Collection interface while enforcing this rule of uniqueness.

Using an Array for Character Frequency 

This approach uses a frequency array to track the occurrence of each character in the string. The array stores whether a character has been seen before.

Following are the steps to Check if a String is a Heterogram using an Array ?

  • Initialize a frequency array for all lowercase English letters.
  • Iterate through the string:
    • For each character, check if it has already appeared.
    • If it has, the string is not a heterogram.
    • Otherwise, mark the character as seen.
  • If no duplicates are found, the string is a heterogram.

Example

Below is the Java program to check whether a given string is a Heterogram or not using Array ?

public class Example {
   public static void main (String[] args) {
      String str = "mango";
      int n = str.length();
      int alphaList[] = new int[26];
      int flag = 1;
      System.out.println("The string is: " + str);
      for (int i = 0; i < n; i++) {
         if (str.charAt(i) != ' ') {
            if (alphaList[str.charAt(i) - 'a'] == 0) {
               alphaList[str.charAt(i) - 'a'] = 1;
         }else {
            flag = 0;
            break;
         }
      }
   }
   if(flag == 1)
      System.out.println("The above string is a Heterogram");
   else
      System.out.println("The above string is not a Heterogram");
   }
}

Output

The string is: mango
The above string is a Heterogram

Using a HashSet

This alternative approach uses a HashSet to track characters, making the logic simple and concise.

HashSet() Class

A HashSet in Java is a collection that stores unique elements using a hash table, ensuring no duplicates and offering fast operations like add, remove, and search. It is unordered and allows one null value.

Following are the steps to Check if a String is a Heterogram using HashSet() Class ?

  • Create an empty HashSet to store characters.
  • Iterate through the string:
    • The string is not a heterogram if a character is already in the set.
    • Otherwise, add the character to the set.
  • If the iteration completes without finding duplicates, the string is a heterogram.

Example

Below is the Java program to check whether a given string is a Heterogram or not using HashSet ?

import java.util.HashSet;
public class HeterogramChecker {
   public static void main(String[] args) {
      String str = "apple";
      HashSet<Character> charSet = new HashSet<>();
      boolean isHeterogram = true;

      System.out.println("The string is: " + str);
      for (char ch : str.toCharArray()) {
         if (ch != ' ') { // Ignore spaces
            if (!charSet.add(ch)) { // If character is already in the set
               isHeterogram = false;
               break;
            }
         }
      }

      if (isHeterogram)
         System.out.println("The above string is a Heterogram");
      else
         System.out.println("The above string is not a Heterogram");
   }
}

Output

The string is: apple
The above string is not a Heterogram

Comparison of Approaches

Feature Frequency Array Approach HashSet Approach
Space Complexity O(1) for array (fixed size)
O(n) for set (dynamic)
Time Complexity O(n)
O(n)
Ease of Use Slightly verbose Concise and intuitive

Conclusion

Both approaches effectively determine if a string is a heterogram. The frequency array is memory-efficient for alphabet-only strings, while the HashSet approach is more versatile for strings with arbitrary characters. 

Alshifa Hasnain
Alshifa Hasnain

Converting Code to Clarity

Updated on: 2024-12-17T03:31:34+05:30

436 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements