First non-repeating character using one traversal of string | Set 2

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’.
 

 

find-first-non-repeated-character-in-a-string

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++

filter_none

edit
close

play_arrow

link
brightness_4
code

// 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;
}

chevron_right


Java

filter_none

edit
close

play_arrow

link
brightness_4
code

// 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));
}
}

chevron_right


Python3

filter_none

edit
close

play_arrow

link
brightness_4
code

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

chevron_right


C#

filter_none

edit
close

play_arrow

link
brightness_4
code

// 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

chevron_right


Output: 

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

filter_none

edit
close

play_arrow

link
brightness_4
code

# 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)

chevron_right


Output: 

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.




My Personal Notes arrow_drop_up

Recommended Posts:


Check out this Author's contributed articles.

If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.

Please Improve this article if you find anything incorrect by clicking on the "Improve Article" button below.



Article Tags :
Practice Tags :


10


Please write to us at contribute@geeksforgeeks.org to report any issue with the above content.