# Find the first non repeating character in a given string

Objective: Given a string, write an algorithm to find the first non repeating character in it.

Example:

```String input = " tutorial horizon"

Output: 'u'

Output: No non-repeating character found.
```

Approach:

Naive approach: This problem can be easily solved using two nested loops. Take each character from the outer loop and check the character in rest of the string using inner loop and check if that character appears again, if yes then continue else return that character.  Time complexity is O(N^2).

Better approach: Using extra space

• Iterate the string from left to right.
• Count the occurrence of each character and store it in a map.
• Iterate the string again from left to right and check if the character has count = 1 one in the map created in the previous step, if yes then return that character.
• If none of the character has count = 1 in map, return null.

Complete Code:

 import java.util.HashMap; public class FirstNonRepeatingCharacter { public static Character getCharacter(String input){ //remove all the spaces input = input.replaceAll(" ", ""); Character nonRptChar = null; //Will store each character and it's count HashMap map = new HashMap(); for (int i = 0; i

```Output:

First Non Repeating Character in 'tutorial horizon' is: u
```

### 3 thoughts on “Find the first non repeating character in a given string”

1. The output says “No repeating character found”.
It should be “No non-repeating character found.”

• Thanks lipsa. Corrected it

2. //O(n*2) complexity.

public class FirstNonRepeatingChar
{

public static void main(String[] args)
{
char[] chars = input.toCharArray();
for(char c : chars) {
if(map.get(c) != null) {
map.put(c, map.get(c) + 1);
} else {
map.put(c, 1);
}
}
//System.out.println(map);
boolean found = false;
for(char c : map.keySet()) {
if(map.get(c) == 1) {
System.out.println(c);
found = true;
break;
}
}
if(!found) {
System.out.println(“No non repeating character found”);
}
}//main
}