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

3 comments:

DevOps 01: What is DevOps and How it benefits organizations?

DevOps is a culture in an organization, where the development team and operations team help each other by sharing information, process and t...