This post is completed by 1 user
|Add to List|
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.
String input = " tutorial horizon" Output: 'u' String input = "aabbccadd" Output: No non-repeating character found.
Naive approach: This problem can be easily solved using two nested loops. Take each character from the outer loop and check the character in the rest of the string using the 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 on 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 characters has count = 1 in the map, return null.
First Non Repeating Character in 'tutorial horizon' is: u