![]() |
VOOZH | about |
Given a string s of lowercase English letters, the task is to find the first non-repeating character. If there is no such character, return '$'.
Examples:
Input: s = "geeksforgeeks"
Output: 'f'
Explanation: 'f' is the first character in the string which does not repeat.Input: s = "racecar"
Output: 'e'
Explanation: 'e' is the only character in the string which does not repeat.Input: "aabbccc"
Output: '$'
Explanation: All the characters in the given string are repeating.
Table of Content
The idea is to use two nested loops, the outer loop for picking an element and the inner loop for finding another occurrence of the picked character in the string. As soon as we find a character which has only one occurrence in the input string, return it. If all characters have multiple occurrences, return '$'.
e
The efficient approach is to either use an array of size MAX_CHAR to store the frequencies of each character. Traverse the input string twice:
- First traversal is to count the frequency of each character.
- Second traversal to find the first character in string with a frequency of one.
f
The above approach can be optimized using a single traversal of the string. The idea is to maintain a visited array of size MAX_CHAR initialized to -1, indicating no characters have been seen yet. Now, we iterate through the string:
- If a character is seen for the first time, its index is stored in the array.
- If the character is found again then its array value is set to -2 to represent this character is now repeating.
After the string traversal, traverse the visited array and check if value in the array is not equal to -1 or -2 (means, this character is not repeating). We then find the smallest positive index from these values to find the first non-repeating character. If no such index is found, return '$'.
$