How to Find Duplicate Characters in String [Java Coding Problems] (original) (raw)
Hello guys, today's programming exercise is to write a program to find repeated characters in a String. For example, if given input to your program is "Java", it should print all duplicates characters, i.e. characters appear more than once in String and their count like a = 2 because of character 'a' has appeared twice in String "Java". This is also a very popular coding question on the various level of Java interviews and written tests, where you need to write code. On the difficulty level, this question is at par with the prime numbers or Fibonacci series, which are also very popular on junior level Java programming interviews and it's expected from every programmer to know how to solve them.
I personally like this exercise because it gives beginners an opportunity to familiarize themselves with the concept of Map data structure, which allows you to store mappings in the form of key and value.
Since Map and Hash table data structure is heavily used in any enterprise Java application, good knowledge of this data structure is highly desirable among any level of Java programmers.
By the way, there are a couple of variants of this problem, which you may want to look at before going for an interview.
Sometimes an interviewer will ask you to read a file and print all duplicate characters and their count, core logic will remain the same, all you need to do is demonstrate how much you know about File IO in Java, like streaming file if it's very large rather than reading the whole file in memory.
Btw, a basic knowledge of data structure and algorithms is needed and if you need to brush up then do so. If you need a resource, I highly recommend checking out Data Structures and Algorithms: Deep Dive Using Java course on Udemy. It's a hands-on course and covers all essential data structures. It's also very affordable and you can get in just $10 on Udemy flash sales which happens every now and then.
Java Program to find Repeated Characters of String [Solution]
The standard way to solve this problem is to get the character array from String, iterate through that and build a Map with character and their count. Then iterate through that Map and print characters which have appeared more than once. So you actually need two loops to do the job, the first loop to build the map and the second loop to print characters and counts.
If you look at the below example, there is only one static method called the printDuplicateCharacters(), which does both these jobs. We first got the character array from String by calling toCharArray().
Next, we are using HashMap to store characters and their count. We use the containsKey() method to check if the key, which is a character that already exists or not already exists we get the old count from HashMap by calling the get() method and store it back after incrementing it by 1.
Once we build our Map with each character and count, the next task is to loop through Map and check each entry, if the count, which is the value of Entry is greater than 1, then that character has occurred more than once. You can now print duplicate characters or do whatever you want with them.
By the way, if you are preparing for coding interviews then I highly recommend you to join Grokking the Coding Interview: Patterns for Coding Questions course on Educative. This is an interactive, text-based coding course to learn 15 essential coding patterns like sliding window, merge interval, fast and slow pointers, etc which can be used to solve 100+ coding problems, and you can get it just for $14.9 per month membership.
And, here is the complete Java program to find duplicate characters in a given String.
import java.util.HashMap; import java.util.Map; import java.util.Scanner; import java.util.Set;
/**
Java Program to find duplicate characters in String.
@author http://java67.blogspot.com */ public class FindDuplicateCharacters{
public static void main(String args[]) { printDuplicateCharacters("Programming"); printDuplicateCharacters("Combination"); printDuplicateCharacters("Java"); }
/*
Find all duplicate characters in a String and print each of them. */ public static void printDuplicateCharacters(String word) { char[] characters = word.toCharArray();
// build HashMap with character and number of times they appear in String Map<Character, Integer> charMap = new HashMap<Character, Integer>(); for (Character ch : characters) { if (charMap.containsKey(ch)) { charMap.put(ch, charMap.get(ch) + 1); } else { charMap.put(ch, 1); } }
// Iterate through HashMap to print all duplicate characters of String Set<Map.Entry<Character, Integer>> entrySet = charMap.entrySet(); System.out.printf("List of duplicate characters in String '%s' %n", word); for (Map.Entry<Character, Integer> entry : entrySet) { if (entry.getValue() > 1) { System.out.printf("%s : %d %n", entry.getKey(), entry.getValue()); } }
}
}
Output List of duplicate characters in String 'Programming' g : 2 r : 2 m : 2 List of duplicate characters in String 'Combination' n : 2 o : 2 i : 2 List of duplicate characters in String 'Java'
That's all on how to find duplicate characters in a String. Next time this question is asked to you in a programming job interview, you can confidently write a solution and can explain them. Remember this question is also asked to write a Java program to find repeated characters of a given String, so don't get confused yourself in wording, the algorithm will remain the same.
Related Data Structure and Algorithm Interview Questions from Javarevisited Blog
- Top 30 Array Coding Interview Questions with Answers (see here)
- How to reverse an array in place in Java? (solution)
- Top 15 Data Structure and Algorithm Interview Questions (see here)
- How to find a missing number in an array? (answer)
- How to compare two arrays in Java? (answer)
- Top 20 String coding interview questions (see here)
- How to remove duplicate elements from an array in Java? (solution)
- How to find all pairs whose sum is equal to a given number in Java (solution)
- Top 30 linked list coding interview questions (see here)
- Top 50 Java Programs from Coding Interviews (see here)
- 5 Free Data Structure and Algorithms Courses for Programmers (courses)
- 10 Algorithms Books Every Programmer Should Read (books)
- 10 Free Data Structure and Algorithm Courses for Programmers (courses)
- 100+ Data Structure Coding Problems from Interviews (questions)
Thanks for reading this article so far. If you like this Java coding problem and my solution then please share it with your friends and colleagues. If you have any questions or doubt then please let us know and I'll try to find an answer for you. As always suggestions, comments, innovative and better answers are most welcome.
P. S. - If you are looking for some Free Algorithms courses to improve your understanding of Data Structure and Algorithms, then you should also check the Data Structure in Java free course on Udemy. It's completely free and all you need to do is create a free Udemy account to enroll in this course.
And, now one question for you, what is your favorite String based coding exercise? reverse String, Palindrome, or this one? or anything else, do let me know in comments.