Sunday, January 27, 2019

Java Program 3: Find first duplicate character in the given string

Let us understand the question first, we have to find the character in the given string which is repeated twice and first. Let us understand with examples:

  • Suppose "Selenium Java" is the given string, in this string 'a' and 'e' repeated twice but 'e' character coming first, so the first duplicate character will be 'e'.
  • Suppose "JEE2 JAVA" is the given string, in this string 'J', 'E" and 'A' repeated twice but 'J' character is coming first, so the first duplicate character is 'J'
Hope the question is clear now, let us implement the logic. We are going to use "HashMap" to solve this question.

Step 1: First we will convert the String to a Character Array

Step 2: Then add each character from the array to HashMap<K, V>  as a key, value pair. While adding the character verify if the character is already present then increase the value by 1, otherwise just add it to HashMap<K, V> with value 1.


Step 3: Finally read each character from the character array and verify whose value is equal to 2, the first matched character will be first duplicate character in the given string.

Execute the above program for different inputs and verify the results.

Some sample outputs are below:


Please let me know if above logic is failing for any of your inputs, I will verify and update. Thanks!!

#HappyLearning #HappyCoding

4 comments:

Java Program 6: How to reverse a String in Java?

In this post we will discuss different methods to reverse a String in java programming. Method 1: Step 1: Read the input string using ...