VOOZH about

URL: https://www.geeksforgeeks.org/dsa/given-a-string-find-its-first-non-repeating-character/

⇱ First non-repeating character of given string - GeeksforGeeks


  • Courses
  • Tutorials
  • Interview Prep

First non-repeating character of given string

Last Updated : 7 Apr, 2025

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.

[Naive Approach] Using Nested Loop – O(n^2) Time and O(1) Space

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 '$'.


Output
e

[Efficient Approach 1] Using Frequency Array (Two Traversal) – O(2*n) Time and O(MAX_CHAR ) Space

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.

Output
f

[Efficient Approach 2] By Storing Indices (Single Traversal) – O(n) Time and O(MAX_CHAR ) Space

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 '$'.



Output
$
Comment