The solution uses a HashMap to store each character as the key and its occurrence count as the value. While traversing the string, the frequency of each character is updated in the map. After processing all characters, the map is traversed again to identify characters whose count is greater than one.
HashMap provides efficient lookup and update operations, making it a suitable choice for frequency counting problems.
Java Solution:
import java.util.HashMap;
import java.util.Map;
public class DuplicateCharacters {
public static void findDuplicateCharacters(String input) {
Map<Character, Integer> characterCountMap = new HashMap<>();
for (char character : input.toCharArray()) {
if (character != ' ') {
characterCountMap.put(
character,characterCountMap.getOrDefault(character, 0) + 1
);
}
}
System.out.println("Duplicate Characters:");
for (Map.Entry<Character, Integer> entry : characterCountMap.entrySet()) {
if (entry.getValue() > 1) {
System.out.println(entry.getKey() + " : " + entry.getValue());
}
}
}
public static void main(String[] args) {
String input = "programming";
findDuplicateCharacters(input);
}
}Output: r : 2 g : 2 m : 2
Time Complexity: O(n), where n is the length of the string since each character is processed once.
Space Complexity: O(k), where k is the number of unique characters stored in the HashMap.
Key Interview Points: • HashMap is commonly used for character frequency counting problems. • The getOrDefault() method simplifies frequency updates. • A common follow-up question is to find the first non-repeated character in a string. • An alternative approach is to use an integer array of size 256 for ASCII characters, which can be more memory efficient for fixed character sets.