Skip to content
Related Articles

Related Articles

Improve Article
First non-repeating character using one traversal of string | Set 2
  • Difficulty Level : Easy
  • Last Updated : 26 May, 2021

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 stores index if an 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

Javascript




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




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

Time Complexity: 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: Give 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:

Java




// Java program for the above approach
public class first_non_repeating {
 
     
    static int firstNonRepeating(String str)
    {
        boolean flag = false;
 
        int index = -1;
 
        for (int i = 0; i < s.length(); i++) {
 
            // Here I am repalcing 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_occurence
                = s.length()
                  - s.replace(
                         Character.toString(s.charAt(i)),
                         "")
                        .length();
 
            if (count_occurence == 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.
Output
First non repeating character is f

Time Complexity: O(N)

Auxiliary Space: O(1)

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.  To complete your preparation from learning a language to DS Algo and many more,  please refer Complete Interview Preparation Course.

In case you wish to attend live classes with industry experts, please refer Geeks Classes Live 

My Personal Notes arrow_drop_up
Recommended Articles
Page :