Given a string, find the first non-repeating character in it. For example, if the input string is “GeeksforGeeks”, then output should be ‘f’ and if input string is “GeeksQuiz”, then output should be ‘G’.
We have discussed two solutions in Given a string, find its first non-repeating character . In this post a further optimized solution (over method 2 of previous post) is discussed. The idea is to optimize space. Instead of using a pair to store count and index, we use single element that store index if element appears once, else stores a negative value.
C++
// CPP program to find first non-repeating // character using 1D array and one traversal. #include <bits/stdc++.h> using namespace std; #define NO_OF_CHARS 256 /* The function returns index of the first non-repeating character in a string. If all characters are repeating then reurns INT_MAX */ int firstNonRepeating( char * str) { // Initialize all characters as // absent. int arr[NO_OF_CHARS]; for ( int i = 0; i < NO_OF_CHARS; i++) arr[i] = -1; // After below loop, the value of // arr[x] is going to be index of // of x if x appears only once. Else // the value is going to be either // -1 or -2. for ( int i = 0; str[i]; i++) { if (arr[str[i]] == -1) arr[str[i]] = i; else arr[str[i]] = -2; } int res = INT_MAX; for ( int i = 0; i < NO_OF_CHARS; i++) // If this character occurs only // once and appears before the // current result, then update the // result if (arr[i] >= 0) res = min(res, arr[i]); return res; } /* Driver program to test above function */ int main() { char str[] = "geeksforgeeks" ; int index = firstNonRepeating(str); if (index == INT_MAX) printf ( "Either all characters are " "repeating or string is empty" ); else printf ( "First non-repeating character" " is %c" , str[index]); return 0; } |
Java
// Java program to find first // non-repeating character // using 1D array and one // traversal. import java.io.*; import java.util.*; import java.lang.*; class GFG { /* The function returns index of the first non-repeating character in a string. If all characters are repeating then returns INT_MAX */ static int firstNonRepeating(String str) { int NO_OF_CHARS = 256 ; // Initialize all characters // as absent. int arr[] = new int [NO_OF_CHARS]; for ( int i = 0 ; i < NO_OF_CHARS; i++) arr[i] = - 1 ; // After below loop, the // value of arr[x] is going // to be index of x if x // appears only once. Else // the value is going to be // either -1 or -2. for ( int i = 0 ; i < str.length(); i++) { if (arr[str.charAt(i)] == - 1 ) arr[str.charAt(i)] = i; else arr[str.charAt(i)] = - 2 ; } int res = Integer.MAX_VALUE; for ( int i = 0 ; i < NO_OF_CHARS; i++) // If this character occurs // only once and appears before // the current result, then // update the result if (arr[i] >= 0 ) res = Math.min(res, arr[i]); return res; } // Driver Code public static void main(String args[]) { String str = "geeksforgeeks" ; int index = firstNonRepeating(str); if (index == Integer.MAX_VALUE) System.out.print( "Either all characters are " + "repeating or string is empty" ); else System.out.print( "First non-repeating character" + " is " + str.charAt(index)); } } |
Python3
''' Python3 implementation to find non repeating character using 1D array and one traversal''' import math as mt NO_OF_CHARS = 256 ''' The function returns index of the first non-repeating character in a string. If all characters are repeating then reurns INT_MAX ''' def firstNonRepeating(strng): #initialize all character as absent arr = [ - 1 for i in range (NO_OF_CHARS)] ''' After below loop, the value of arr[x] is going to be index of of x if x appears only once. Else the value is going to be either -1 or -2.''' for i in range ( len (strng)): if arr[ ord (strng[i])] = = - 1 : arr[ ord (strng[i])] = i else : arr[ ord (strng[i])] = - 2 res = 10 * * 18 for i in range (NO_OF_CHARS): ''' If this character occurs only once and appears before the current result, then update the result''' if arr[i]> = 0 : res = min (res,arr[i]) return res #Driver prohram to test above function strng = "geeksforgeeks" index = firstNonRepeating(strng) if index = = 10 * * 18 : print ( "Either all characters are repeating or string is empty" ) else : print ( "First non-repeating character is" ,strng[index]) #this code is contributed by Mohit Kumar 29 |
C#
// C# program to find first // non-repeating character // using 1D array and one // traversal. using System; class GFG { /* The function returns index of the first non-repeating character in a string. If all characters are repeating then returns INT_MAX */ static int firstNonRepeating(String str) { int NO_OF_CHARS = 256; // Initialize all characters // as absent. int []arr = new int [NO_OF_CHARS]; for ( int i = 0; i < NO_OF_CHARS; i++) arr[i] = -1; // After below loop, the // value of arr[x] is going // to be index of x if x // appears only once. Else // the value is going to be // either -1 or -2. for ( int i = 0; i < str.Length; i++) { if (arr[str[i]] == -1) arr[str[i]] = i; else arr[str[i]] = -2; } int res = int .MaxValue; for ( int i = 0; i < NO_OF_CHARS; i++) // If this character occurs // only once and appears before // the current result, then // update the result if (arr[i] >= 0) res = Math.Min(res, arr[i]); return res; } // Driver Code public static void Main() { String str = "geeksforgeeks" ; int index = firstNonRepeating(str); if (index == int .MaxValue) Console.Write( "Either all characters are " + "repeating or string is empty" ); else Console.Write( "First non-repeating character" + " is " + str[index]); } } // This code is contributed by Rajput-Ji |
First non-repeating character is f
Time Complexity: O(n)
Alternate Implementation
This is coded using a HashMap or Hashing Technique.
If the element(or key) repeats in the string the HashMap (or Dictionary) will change the value of that key to None.
This way we will later on only be finding keys whose value is “not None”.
Python3
# Python implementation of # above approach from collections import Counter def makeHashMap(string): # Use Counter to make a frequency # dictionary of characters in a string. d1 = Counter(string) # Update value of each key such that # if frequency of frequency of a key # is equal to 1, then it is set to 0, # else set the value equal to None d1 = {(key):( 0 if d1[key] = = 1 else None ) for key, value in d1.items()} return d1 def firstNotRepeatingCharacter(s): d = makeHashMap(s) # variable to store the first # non repeating character. nonRep = None # Traversing through the string only once. for i in s: if d[i] is not None : ''' As soon as the first character in the string is found whose value in the HashMap is "not None", that is our first non-repeating character. So we store it in nonRep and break out of the loop. Thus saving on time. ''' nonRep = i break if nonRep is not None : return nonRep else : # If there are no non-repeating characters # then "_" is returned return str ( "_" ) # Driver Code print (firstNotRepeatingCharacter( 'bbcdcca' )) #This code is contributed by Vivek Nigam (@viveknigam300) |
d
Time Complexity: O(N)
Attention reader! Don’t stop learning now. Get hold of all the important DSA concepts with the DSA Self Paced Course at a student-friendly price and become industry ready.