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
!D 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)



My Personal Notes arrow_drop_up

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.



Improved By : mohit kumar 29, Rajput-Ji