Print duplicate characters in a string



We have a string expression consisting of various characters in it. We want to count the repeated characters in this string and print it.

 

Example

String expression = "test string";
Here, the character 't' appears 3 times and 's' appears 2 times

 

Approach

  1. Create an empty Map to store character counts.
  2. Loop through each character in the input string.
  3. For each character encountered:
  1. Check if it's already in the data structure (the map).
  2. If it's not in the map, add it to the map with a count of 1.
  3. If it's already in the map, increment its count by 1.
  1. After processing the entire string:
  1. Examine the map.
  2. Identify characters with counts greater than 1; these are duplicates.
  1. Print or store the duplicate characters identified.

 

Complexity

  • Time Complexity: O(N), where N is the length of the input string.
  • Space Complexity: O(K), where K is the size of the map.

 

Java Code
import java.util.HashMap;
import java.util.Map;

public class CountRepeatedChars {

    public static void printDuplicateCharactersWithCount(String inputString) {

        char[] characters = inputString.toCharArray();
        Map<Character, Integer> charCountMap = new HashMap<>();

        // Count the occurrences of each character in the string
        for (char c : characters) {
            if (Character.isLetter(c)) { // Ignore non-letter characters if desired
                charCountMap.put(c, charCountMap.getOrDefault(c, 0) + 1);
            }
        }

        // Print characters with counts greater than 1 (duplicates)
        for (Map.Entry<Character, Integer> entry : charCountMap.entrySet()) {
            if (entry.getValue() > 1) {
                System.out.println("Character: " + entry.getKey() + ", Count: " + entry.getValue());
            }
        }
    }

    public static void main(String[] args) {

        String inputString = "test string";
        System.out.println("Duplicate characters in string \"" + inputString + "\" with their counts:");
        printDuplicateCharactersWithCount(inputString);
    }
}

Output

Duplicate characters in string "test string" with their counts:
Character: s, Count: 2
Character: t, Count: 3



Thanks for feedback.



Read More....
Find the no of islands in a 2D Array/Matrix
3 Sum
4 Sum - Find four elements that sum to a given target value
Chocolate Distribution Problem
Find the missing number in a sorted array
Best Time to Buy and Sell Stock