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 stores index if an element appears once, else stores a negative value.
Implementation:
// 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 returns 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)
cout << "Either all characters are "
"repeating or string is empty" ;
else
cout << "First non-repeating character"
" is " << str[index];
return 0;
} // This code is contributed by shivanisinghss210 |
// CPP program to find first non-repeating // character using 1D array and one traversal. #include <limits.h> #include <stdio.h> #include <math.h> #define NO_OF_CHARS 256 /* The function returns index of the first non-repeating character in a string. If all characters are repeating then returns 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 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 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 returns INT_MAX ''' def firstNonRepeating(string):
#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 (string)):
if arr[ ord (string[i])] = = - 1 :
arr[ ord (string[i])] = i
else :
arr[ ord (string[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 program to test above function string = "geeksforgeeks"
index = firstNonRepeating(string)
if index = = 10 * * 18 :
print ( "Either all characters are repeating or string is empty" )
else :
print ( "First non-repeating character is" ,string[index])
#this code is contributed by Mohit Kumar 29 |
// 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 |
<script> // JavaScript program to find first // non-repeating character // using 1D array and one // traversal. /* The function returns index
of the first non-repeating character in a string. If all characters are repeating then returns INT_MAX */ function firstNonRepeating(str)
{
let NO_OF_CHARS = 256;
// Initialize all characters
// as absent.
let arr = new Array(NO_OF_CHARS);
for (let 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 (let i = 0;
i < str.length; i++)
{
if (arr[str[i].charCodeAt(0)] == -1)
arr[str[i].charCodeAt(0)] = i;
else
arr[str[i].charCodeAt(0)] = -2;
}
let res = Number.MAX_VALUE;
for (let 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
let str = "geeksforgeeks" ;
let index = firstNonRepeating(str);
if (index == Number.MAX_VALUE)
document.write( "Either all characters are " +
"repeating or string is empty" );
else
document.write( "First non-repeating character" +
" is " + str[index]);
// This code is contributed by patel2127 </script> |
First non-repeating character is f
Time Complexity: O(n)
Auxiliary Space: O(1)
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”.
Implementation:
// C++ implementation of // above approach #include <bits/stdc++.h> #include <unordered_map> using namespace std;
// Function to make a frequency // dictionary of characters in a string. unordered_map< char , int > makeHashMap(string string)
{ // Create an empty HashMap
unordered_map< char , int > d1;
// To store each character and its frequency
char c;
// Traversing through the string
for ( int i = 0; i < string.length(); i++) {
// Extracting each character
c = string[i];
// If the character has occurred before
if (d1.find(c) != d1.end()) {
// Increment its frequency
d1++;
}
// If the character has not occurred before
else
d1 = 1;
}
// 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
for ( auto it = d1.begin(); it != d1.end(); it++)
{
if (it->second == 1)
it->second = 0;
else
it->second = -1;
}
return d1;
} // Function to return the first // non repeating character char firstNotRepeatingCharacter(string s)
{ // Make a frequency dictionary
unordered_map< char , int > d = makeHashMap(s);
// Variable to store the result
char nonRep = '.' ;
// Traversing through the string only once
for ( int i = 0; i < s.length(); i++) {
char c = s[i];
// If the character's value in the
// frequency dictionary is "not None"
if (d == 0) {
// Store it in the result
nonRep = c;
// Break out of the loop
break ;
}
}
// If no non-repeating character is found
if (nonRep == '.' )
return '_' ;
else
return nonRep;
} // Driver Code int main()
{ string s = "bbcdcca" ;
cout << firstNotRepeatingCharacter(s);
return 0;
} |
// Java implementation of // above approach import java.util.HashMap;
class GFG {
// Function to make a frequency
// dictionary of characters in a string.
public static HashMap<Character, Integer> makeHashMap(String string)
{
// Create an empty HashMap
HashMap<Character, Integer> d1 =
new HashMap<Character, Integer>();
// To store each character and its frequency
char c;
// Traversing through the string
for ( int i = 0 ; i < string.length(); i++) {
// Extracting each character
c = string.charAt(i);
// If the character has occurred before
if (d1.containsKey(c)) {
// Increment its frequency
Integer oldValue = d1.get(c);
d1.put(c, oldValue + 1 );
}
// If the character has not occurred before
else
d1.put(c, 1 );
}
// 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
for (Character key : d1.keySet()) {
if (d1.get(key) == 1 )
d1.put(key, 0 );
else
d1.put(key, null );
}
return d1;
}
// Function to return the first
// non repeating character
public static Character firstNotRepeatingCharacter(String s)
{
// Make a frequency dictionary
HashMap<Character, Integer> d = makeHashMap(s);
// Variable to store the result
Character nonRep = null ;
// Traversing through the string only once
for ( int i = 0 ; i < s.length(); i++) {
Character c = s.charAt(i);
// If the character's value in the
// frequency dictionary is "not None"
if (d.get(c) != null ) {
// Store it in the result
nonRep = c;
// Break out of the loop
break ;
}
}
// If no non-repeating character is found
if (nonRep == null )
return '_' ;
else
return nonRep;
}
// Driver Code
public static void main(String args[])
{
String s = "bbcdcca" ;
System.out.println(firstNotRepeatingCharacter(s));
}
} |
# 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) |
using System;
using System.Collections.Generic;
public class Program {
// Function to create a Dictionary with characters and
// their frequency
public static Dictionary< char , int >
MakeHashMap( string s)
{
// Initializing an empty dictionary
var d1 = new Dictionary< char , int >();
// Iterating through each character in the string
foreach ( char c in s)
{
// If the character is already in the
// dictionary, increment its frequency
if (d1.ContainsKey(c)) {
d1++;
}
// Else add the character with frequency 1 to
// the dictionary
else {
d1 = 1;
}
}
// Initializing another empty dictionary for marking
// repeated characters
var d2 = new Dictionary< char , int >();
// Iterating through each key-value pair in the
// first dictionary
foreach ( var kvp in d1)
{
// If the character occurs only once, set its
// value to 0 in the second dictionary
if (kvp.Value == 1) {
d2[kvp.Key] = 0;
}
// Else set its value to -1 in the second
// dictionary
else {
d2[kvp.Key] = -1;
}
}
// Return the second dictionary
return d2;
}
// Function to find the first non-repeating character in
// the given string
public static char FirstNotRepeatingCharacter( string s)
{
// Create a dictionary with the frequency of each
// character
var d = MakeHashMap(s);
// Variable to store the first non-repeating
// character
char nonRep = '.' ;
// Iterate through each character in the string
foreach ( char c in s)
{
// If the frequency of the character is 0, it is
// non-repeating
if (d == 0) {
// Store the non-repeating character and
// break out of the loop
nonRep = c;
break ;
}
}
// If no non-repeating character is found, return
// '_'
if (nonRep == '.' ) {
return '_' ;
}
else {
// Else return the first non-repeating character
return nonRep;
}
}
// Main method
public static void Main()
{
string s = "bbcdcca" ;
Console.WriteLine(FirstNotRepeatingCharacter(s));
}
} |
// Javascript implementation of // above approach function makeHashMap(string) {
// Use Map to make a frequency
// dictionary of characters in a string.
let d1 = new Map();
for (let i = 0; i < string.length; i++) {
let char = string.charAt(i);
if (d1.has(char)) {
d1.set(char, d1.get(char) + 1);
} else {
d1.set(char, 1);
}
}
// Update value of each key such that
// if frequency of a key is equal to 1, then it is set to 0,
// else set the value equal to null
d1.forEach( function (value, key) {
if (value === 1) {
d1.set(key, 0);
} else {
d1.set(key, null );
}
});
return d1;
} function firstNotRepeatingCharacter(s) {
let d = makeHashMap(s);
// variable to store the first
// non repeating character.
let nonRep = null ;
// Traversing through the string only once.
for (let i = 0; i < s.length; i++) {
let char = s.charAt(i);
if (d.get(char) !== null ) {
/*
As soon as the first character in the string is
found whose value in the HashMap is "not null",
that is our first non-repeating character.
So we store it in nonRep and break out of the
loop. Thus saving on time.
*/
nonRep = char;
break ;
}
}
if (nonRep !== null ) {
return nonRep;
} else {
// If there are no non-repeating characters
// then "_" is returned
return "_" ;
}
} // Driver code console.log(firstNotRepeatingCharacter( "bbcdcca" ));
// This code is contributed by Prajwal Kandekar |
d
Time Complexity: O(N)
Auxiliary Space: O(N)
Method 3: Another simple approach to this problem without using any hashmap or array is mentioned below. We can find the first non-repeating character by just using single for loop.
Another Approach:
To count the frequency of character we can do the following step:
frequency of a character = length_of_string – length_of_string_without_that _character
for example: Given String is “helloh” and we want to count frequency of character “h” so by using the above formula we can say
frequency of character “h” = 6(length of string) – 4(length of string without “h”) = 2
So by this way, we can count the frequency of every character in a string and then if we found count == 1 that means that character is the first non-repeating character in the string.
Implementation: Implementation of the above method in java is shown below:
#include<bits/stdc++.h> using namespace std;
// C++ implementation of above approach void firstNonRepeating(string s)
{ bool flag = false ;
int index = -1;
for ( int i = 0; i < s.size(); i++) {
// Here I am replacing a character with "" and
// then finding the length after replacing and
// then subtracting length of that replaced
// string from the total length of the original
// string
string temp = s;
temp.erase( remove (temp.begin(), temp.end(), s[i]), temp.end());
int count_occurrence = s.size() - temp.size();
if (count_occurrence == 1)
{
flag = true ;
index = i;
break ;
}
}
if (flag)
cout << "First non repeating character is " << s[index] << endl;
else
cout << "There is no non-repeating character is present in the string" << endl;
} int main(){
// Driver Code
string s = "GeeksforGeeks" ;
firstNonRepeating(s);
return 0;
} // The code is contributed by Nidhi goel. |
// Java program for the above approach public class first_non_repeating {
static void firstNonRepeating(String s)
{
boolean flag = false ;
int index = - 1 ;
for ( int i = 0 ; i < s.length(); i++) {
// Here I am replacing a character with "" and
// then finding the length after replacing and
// then subtracting length of that replaced
// string from the total length of the original
// string
int count_occurrence
= s.length()
- s.replace(
Character.toString(s.charAt(i)),
"" )
.length();
if (count_occurrence == 1 ) {
flag = true ;
index = i;
break ;
}
}
if (flag)
System.out.println(
"First non repeating character is "
+ s.charAt(index));
else
System.out.println(
"There is no non-repeating character is present in the string" );
}
// Driver Code
public static void main(String arg[])
{
String s = "GeeksforGeeks" ;
firstNonRepeating(s);
}
} // This Solution is contributed by Sourabh Sharma. |
# Python implementation of above approach def firstNonRepeating(s):
flag = False
index = - 1
for i in range ( len (s)):
# Here I am replacing a character with "" and
# then finding the length after replacing and
# then subtracting length of that replaced
# string from the total length of the original
# string
count_occurrence = len (s) - len (s.replace(s[i],''))
if (count_occurrence = = 1 ):
flag = True
index = i
break
if (flag):
print (f "First non repeating character is {s[index]}" )
else :
print ( "There is no non-repeating character is present in the string" )
# Driver Code s = "GeeksforGeeks"
firstNonRepeating(s) # This code is contributed by shinjanpatra |
// C# program for the above approach using System;
class first_non_repeating {
static void firstNonRepeating( string s)
{
bool flag = false ;
int index = -1;
for ( int i = 0; i < s.Length; i++) {
// Here I am replacing a character with "" and
// then finding the length after replacing and
// then subtracting length of that replaced
// string from the total length of the original
// string
int count_occurrence
= s.Length
- s.Replace(Char.ToString(s[i]), "" )
.Length;
if (count_occurrence == 1) {
flag = true ;
index = i;
break ;
}
}
if (flag) {
Console.WriteLine(
"First non repeating character is "
+ s[index]);
}
else {
Console.WriteLine(
"There is no non-repeating character is present in the string" );
}
}
// Driver Code
public static void Main()
{
string s = "GeeksforGeeks" ;
firstNonRepeating(s);
}
} // This Solution is contributed by Samim Hossain Mondal. |
<script> // JavaScript implementation of above approach function firstNonRepeating(s)
{ let flag = false ;
let index = -1;
for (let i = 0; i < s.length; i++) {
// Here I am replacing a character with "" and
// then finding the length after replacing and
// then subtracting length of that replaced
// string from the total length of the original
// string
let count_occurrence
= s.length - s.replaceAll(s[i], '' ).length;
if (count_occurrence == 1)
{
flag = true ;
index = i;
break ;
}
}
if (flag)
document.write(
"First non repeating character is "
+ s[index], "</br>" );
else
document.write(
"There is no non-repeating character is present in the string" , "</br>" );
} // Driver Code let s = "GeeksforGeeks"
firstNonRepeating(s) // This code is contributed by shinjanpatra </script> |
First non repeating character is f
Time Complexity: O(N)
Auxiliary Space: O(1)