Problem :

Write a java program to find duplicate characters and their count in a given string? For example, in a word “Mississippi”, duplicate characters and their count is i : 4 s : 4 and p : 2.

The logic behind finding duplicate characters and their count in a string can be broken down into these steps:

  1. Character Counting:
    • We create a data structure to store the count of each character encountered in the string. In the provided code, an integer array (charCounts) of size 256 is used. This assumes the string uses ASCII characters, where each character has a unique numerical representation between 0 and 255.
    • We iterate through each character in the string. This can be done efficiently by converting the string to a character array using str.toCharArray().
    • For each character, we access the corresponding index in the charCounts array and increment its value by 1. This effectively keeps track of how many times each character appears in the string.
  2. Identifying Duplicates:
    • After iterating through the entire string, the charCounts array holds the count of each character.
    • We iterate through the charCounts array again.
    • For each element (representing a character count), we check if the value is greater than 1. If it is, it means the corresponding character appeared more than once in the original string.
  3. Printing Results:
    • If a character count is greater than 1 (indicating a duplicate), we retrieve the actual character from its index in the charCounts array using type casting ((char) i).
    • We then print the character along with its count from the charCounts array.

This approach efficiently identifies duplicate characters and their occurrences in a string using a single loop for counting and another for identifying duplicates.

Java Program To Find Duplicate Characters In A String :

public class FindDuplicateChars {

  public static void main(String[] args) {
    String str = "This is a sample string"; // Example string
    countDuplicateChars(str);
  }

  public static void countDuplicateChars(String str) {
    // Create an array to store character counts (assuming ASCII characters)
    int[] charCounts = new int[256];

    // Traverse the string and increment count for each character
    for (char c : str.toCharArray()) {
      charCounts[c]++;
    }

    // Print duplicate characters and their counts
    System.out.println("Duplicate characters and their count:");
    for (int i = 0; i < charCounts.length; i++) {
      if (charCounts[i] > 1) {
        System.out.println((char) i + " : " + charCounts[i]);
      }
    }
  }
}

There is another way to find out the duplicates using Hashmap

import java.util.HashMap;
import java.util.Map;

public class FindDuplicateChars {

  public static void main(String[] args) {
    String str = "Hello, World!"; // Example string
    countDuplicateChars(str);
  }

  public static void countDuplicateChars(String str) {
    // Create a HashMap to store character counts
    Map<Character, Integer> charCounts = new HashMap<>();

    // Traverse the string and update count in HashMap
    for (char c : str.toCharArray()) {
      if (charCounts.containsKey(c)) {
        charCounts.put(c, charCounts.get(c) + 1);
      } else {
        charCounts.put(c, 1);
      }
    }

    // Print duplicate characters and their counts
    System.out.println("Duplicate characters and their count:");
    for (Map.Entry<Character, Integer> entry : charCounts.entrySet()) {
      if (entry.getValue() > 1) {
        System.out.println(entry.getKey() + " : " + entry.getValue());
      }
    }
  }
}

LOGIC Behind this Program –

The logic behind finding duplicate characters and their count in a string using a HashMap can be broken down into these steps:

  1. HashMap for Character Counts:
    • We utilize a HashMap named charCounts to store the frequency of each character encountered in the string. In this HashMap:
      • The key represents the unique character itself (Character).
      • The value associated with the key represents the number of times that character appears in the string (Integer).
  2. Iterating and Updating Counts:
    • We iterate through each character in the string, typically using a character array obtained from the string using toCharArray().
    • For each character (c):
      • We check if the HashMap already contains the character as a key using the containsKey(c) method.
        • If the character is present (key exists):
          • We retrieve the current count associated with that character using the get(c) method.
          • We increment the count by 1 to reflect the additional occurrence of the character.
          • We update the value for the existing key in the HashMap using the put(c, count + 1) method.
        • If the character is not present (new key):
          • We add a new key-value pair to the HashMap using the put(c, 1) method. Here, c is the character, and 1 is its initial occurrence.
  3. Identifying and Printing Duplicates:
    • After iterating through the entire string, the charCounts HashMap holds the count for each unique character.
    • We iterate through the charCounts HashMap using a loop on its entrySet(). This method returns a set of key-value pairs (entries) in the HashMap.
    • For each entry in the HashMap:
      • We access the value (count) associated with the character using the getValue() method of the Map.Entry object.
      • If the count is greater than 1 (indicating a duplicate character), we access the character itself using the getKey() method of the Map.Entry object.
      • Finally, we print the character and its count retrieved from the HashMap entry.

This approach leverages the efficient key-value lookup capabilities of a HashMap to effectively track character occurrences and identify duplicates in the string.

Categories: Blog

1 Comment

60+ Latest Java Interview Programs With Solutions 2024 - Divi Tech HR Solutions · March 17, 2024 at 17:44

[…] Write a Java program to find duplicate characters and their count in a given string. For example, in a string “Mississippi”, duplicate characters and their count is i : 4 s : 4 and p : 2. [Solution] […]

Leave a Reply

Avatar placeholder

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