Find First Non-repeating Character in a String – Java Code

Write a java program to find first non-repeating character in a string. Given an input string, Write a java code to find first non-repeating character in a string.

For example –

i) Input string – java
Output – j (j is the first non-repeating character)

ii) Input string – web rewrite
Output – b (b is the first non-repeating character)

Java Program to Find the First Non-repeated Character in a String

Find First Non-repeating Character in a String

Let’s first think how do you approach this problem. Which data structure should you use and why?

Programming video tutorials

Find First Non-repeating character in a String using HashMap – Java Code

The simplest solution is to use HashMap to find first non-repeating character in a String. Here is the algorithm to find first non repeating character.

a) Traverse a String and store each character and it’s count in a HashMap.
b) Now, we know each character and it’s count. Let’s traverse a string again and check the count for each character in a Map. Once we found the character with count 1, just break the loop and return that character.

We are traversing the string again from first to the last character as HashMap doesn’t maintain the insertion order. 

Java Program to Find First Non-repeating character in a String using LinkedHashMap

In this solution, we are going to use LinkedHashMap to store character and it’s count. The advantage of using LinkedHashMap is that it maintains the insertion order. So, once we traversed the string and created the map of a character and it’s count, we just need to iterate through LinkedHashMap again and choose the first entry with a value 1.

1) Traverse a string and create a map for character and it’s count.
2) Loop through LinkedHashMap to find an entry with a value 1.

Programming questions on stack

Programming questions on a linked list

Find First Non-Repeating Character in a String – Video Tutorial

In this video tutorial, I have explained how we can first non-repeating character in a string using HashMap and LinkedHashMap.

Conclusion

I have explained java program to find the first non-repeated character in a string using HashMap and LinkedHashMap. If you know some other efficient way to solve this problem you can let us know through your comments.

Tagged , , , . Bookmark the permalink.

About WebRewrite

I am technology lover who loves to keep updated with latest technology. My interest field is Web Development.