Find Duplicate Characters in a String

Solution Steps

  1. Obtain char array from the input String
  2. Loop through the char array, check if the list(List<Character>) already contains the char
    • If No, add the char to the list
    • If Yes, add the char to the duplicates Set<Character>
  3. The elements present in the duplicates Set gives us the required output.

package com.java.programs;
import java.util.ArrayList;
import java.util.List;
import java.util.Set;
import java.util.TreeSet;
public class DuplicateCharacters {
	public static Set<Character> duplicateCharacters(String input) {
		List<Character> list = new ArrayList<>();
		Set<Character> duplicates = new TreeSet<>();
		for (char c : input.toCharArray()) {
			if (list.contains(c)) {
				duplicates.add(c);
			} else {
				list.add(c);
			}
		}
		return duplicates;
	}
	public static void main(String[] args) {
		System.out.println(duplicateCharacters("aeroplane"));
	}
}
[a, e]

Leave a Reply

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