Find first non repeated character in a String

One of the interview question is “How will you find first non repeating character in String.”
For example:
If input string is “analogy”,  then program should return ‘n’
If input string is “easiest”, then program should return ‘a’

First approach:

We will use LinkedHashMap to find first non repeating character in String.

Algorithm:

  • Get character while looping over String
  • Put this character in LinkedHashMap with count. If character is already there, increase count by 1.
  • Get count from LinkedHashMap while iterating. If count is 1,return that character as LinkedHashMap maintains insertion order.

Program:

When you run above program, you will get following output:

Second Approach:

Algorithm:

  • Iterate through each character of string.
  • If lastIndexOf and indexOf return same value, then it is first non repeating character in the String.

Program:

When you run above program, you will get following output:

Please go through Common java interview Programs for more such programs.

Add Comment