Open In App

Find first non-repeating character of given String

Improve
Improve
Improve
Like Article
Like
Save Article
Save
Share
Report issue
Report

Given a string S consisting of lowercase Latin Letters, the task is to find the first non-repeating character in S.

Examples: 

Input: “geeksforgeeks”
Output: f
Explanation: As ‘f’ is first character in the string which does not repeat.

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

Input: “algorithm”
Output: a
Explanation: As ‘a’ is first character in the string which does not repeat.

Naive Approach:

The idea is to loop over the string and for every character check the occurrence of the same character in the string. If the count of its occurrence is 1 then return that character. Otherwise, search for the remaining characters.

Note: In python to find the occurrence of a character in the string there is an In-Built Function string.count().

Below is the implementation of the above approach:

C++




#include <bits/stdc++.h>
using namespace std;
 
int main()
{
    string string = "geeksforgeeksfor";
    int index = -1;
    char fnc = ' ';
      
    if(string.size()==0){
      cout<<"EMPTY STRING"<<endl;
    }
   
    for (auto i : string) {
        if (count(string.begin(), string.end(), i) == 1) {
            fnc = i;
            break;
        }
        else {
            index += 1;
        }
    }
    if (index == string.size()-1) {
        cout << "All characters are repeating" << endl;
    }
    else {
        cout << "First non-repeating character is " << fnc
             << endl;
    }
    return 0;
}
 
// This code is contributed by aakansharao1111


Java




//Java code for the above approach
 
import java.io.*;
 
public class GFG {
    public static void main(String[] args) {
        String string = "geeksforgeeks";
        int index = -1;
        char fnc = ' ';
       
       if(string.length()==0){
         System.out.println("EMPTY STRING");
       }
       
        for (char i : string.toCharArray()) {
            if (string.indexOf(i) == string.lastIndexOf(i)) {
                fnc = i;
                break;
            }
            else {
                index += 1;
            }
        }
        if (index == string.length()-1) {
            System.out.println("All characters are repeating");
        }
        else {
            System.out.println("First non-repeating character is " + fnc);
        }
    }
}
 
// This code is contributed by aakansharao1111


Python3




# Python program to print the first non-repeating character
 
string = "geeksforgeeks"
index = -1
fnc = ""
 
if len(string) == 0 :
  print("EMTPY STRING");
 
for i in string:
    if string.count(i) == 1:
        fnc += i
        break
    else:
        index += 1
if index == len(string)-1 :
    print("All characters are repeating ")
else:
    print("First non-repeating character is", fnc)
 
#// This code is contributed by aakansharao1111


C#




// C# implementation of the above approach
 
using System;
using System.Collections.Generic;
using System.Linq;
 
class Gfg
{
    public static void Main(string[] args)
    {
        string str = "geeksforgeeks";
        int index = -1;
        char fnc = ' ';
         
        if(str.Length == 0){
          Console.WriteLine ("EMPTY STRING");
        }
       
        foreach (char i in str)
        {
            if(str.Count(t => t == i)==1){
                fnc = i;
                break;
            }
            else {
                index += 1;
            }
        }
        if (index == str.Length-1) {
            Console.WriteLine("All characters are repeating ");
        }
        else {
            Console.WriteLine("First non-repeating character is " + fnc);
        }
    }
}
 
// This code is contributed by aakansharao1111


Javascript




const string = "geeksforgeeks";
let index = -1;
let fnc = ' ';
 
if(string.length == 0){
console.log("EMPTY STRING");
}
 
for (let i of string) {
    if (string.split(i).length - 1 === 1) {
        fnc = i;
        break;
    } else {
        index += 1;
    }
}
if (index === string.length-1) {
    console.log("All characters are repeating.");
} else {
    console.log(`First non-repeating character is ${fnc}`);
}
 
// This code is contributed by aakansharao1111


Output

All characters are repeating


Time Complexity: O(N2), Traverse over the string for every character in the string of size N.
Auxiliary Space: O(1)

First non-repeating character using string function find():

The idea is to search for the current character in the string just after its first occurrence in the string. If the character is found in the remaining string then return that character. 

The searching is done using in-built find() function.

Below is the implementation of the approach.

C++




// C++ implementation
 
#include <bits/stdc++.h>
using namespace std;
 
void FirstNonRepeat(string s)
{
 
    for (int i = 0; i < s.length(); i++) {
 
        if (s.find(s[i], s.find(s[i]) + 1)
            == string::npos) {
            cout << "First non-repeating character is "
                 << s[i];
 
            return;
        }
    }
    cout << "Either all characters are repeating or "
            "string is empty";
    return;
}
 
// driver code
int main()
{
 
    string s = "geeksforgeeks";
    FirstNonRepeat(s);
}
 
// This code is contributed by shinjanpatra


Java




/*package whatever //do not write package name here */
import java.util.*;
 
class GFG {
 
  // Function which repeats
  // first Nonrepeating character
  public static void FirstNonRepeat(String s)
  {
 
    for (int i = 0; i < s.length(); i++) {
 
      if (s.indexOf(s.charAt(i), s.indexOf(s.charAt(i)) + 1) == -1) {
        System.out.println("First non-repeating character is "+ s.charAt(i));
        break;
      }
    }
    return;
  }
  public static void main (String[] args) {
    String s = "geeksforgeeks";
    FirstNonRepeat(s);
  }
}
 
// This code is contributed by aadityaburujwale.


Python3




# python3 implementation
 
 
def FirstNonRepeat(s):
 
    for i in s:
 
        if (s.find(i, (s.find(i)+1))) == -1:
 
            print("First non-repeating character is", i)
 
            break
 
    return
 
# __main__
 
 
s = 'geeksforgeeks'
 
FirstNonRepeat(s)


C#




// C# program to find first non-repeating
// character
using System;
 
public static class GFG {
 
    // Function which repeats
    // first Nonrepeating character
    public static void FirstNonRepeat(string s)
    {
 
        for (int i = 0; i < s.Length; i++) {
 
            if (s.IndexOf(s[i], s.IndexOf(s[i]) + 1)
                == -1) {
                Console.Write(
                    "First non-repeating character is "
                    + s[i]);
 
                break;
            }
        }
        return;
    }
 
    // driver code
    internal static void Main()
    {
 
        string s = "geeksforgeeks";
        FirstNonRepeat(s);
    }
}
 
// This code is contributed by Aarti_Rathi


Javascript




<script>
 
// JavaScript implementation
 
function FirstNonRepeat(s){
 
   for(let i = 0; i < s.length; i++)
   {
 
       if (s.indexOf(s.charAt(i),s.indexOf(s.charAt(i))+1) == -1)
       {
           document.write(s[i])
 
           break
       }
   }
   return
}
 
// driver code
let s = 'geeksforgeeks'
FirstNonRepeat(s)
 
// This code is contributed by shinjanpatra
 
</script>


Output

First non-repeating character is f

Time Complexity: O(N2)
Auxiliary Space: O(1)

First non-repeating character using HashMap and two string traversals.

The idea is to find the frequency of all characters in the string and check which character has a unit frequency. This task could be done efficiently using a hash_map which will map the character to their respective frequencies and in which we can simultaneously update the frequency of any character we come across in constant time.

Follow the steps below to solve the problem:

  • Make a hash_map that will map the character to their respective frequencies.
  • Traverse the given string using a pointer.
  • Increase the count of the current character in the hash_map.
  • Now traverse the string again and check whether the current character hashfrequency=1.
  • If the frequency>1 continue the traversal.
  • Else break the loop and print the current character as the answer.

Below is the implementation of the above approach.

C++




// C++ program to find first
// non-repeating character
#include <iostream>
using namespace std;
#define NO_OF_CHARS 256
 
/* Returns an array of size 256 containing count
of characters in the passed char array */
int* getCharCountArray(char* str)
{
    int* count = (int*)calloc(sizeof(int), NO_OF_CHARS);
    int i;
    for (i = 0; *(str + i); i++)
        count[*(str + i)]++;
    return count;
}
 
/* The function returns index of first
non-repeating character in a string. If all
characters are repeating then returns -1 */
int firstNonRepeating(char* str)
{
    int* count = getCharCountArray(str);
    int index = -1, i;
 
    for (i = 0; *(str + i); i++) {
        if (count[*(str + i)] == 1) {
            index = i;
            break;
        }
    }
 
    // To avoid memory leak
    free(count);
    return index;
}
 
/* Driver program to test above function */
int main()
{
    char str[] = "geeksforgeeks";
    int index = firstNonRepeating(str);
    if (index == -1)
        cout << "Either all characters are repeating or "
                "string is empty";
    else
        cout << "First non-repeating character is "
             << str[index];
    getchar();
    return 0;
}
 
// This code is contributed by shivanisinghss2110


C




// C program to find first
// non-repeating character
#include <stdio.h>
#include <stdlib.h>
#define NO_OF_CHARS 256
 
/* Returns an array of size 256 containing count
   of characters in the passed char array */
int* getCharCountArray(char* str)
{
    int* count = (int*)calloc(sizeof(int), NO_OF_CHARS);
    int i;
    for (i = 0; *(str + i); i++)
        count[*(str + i)]++;
    return count;
}
 
/* The function returns index of first
   non-repeating character in a string. If all
   characters are repeating then returns -1 */
int firstNonRepeating(char* str)
{
    int* count = getCharCountArray(str);
    int index = -1, i;
 
    for (i = 0; *(str + i); i++) {
        if (count[*(str + i)] == 1) {
            index = i;
            break;
        }
    }
 
    // To avoid memory leak
    free(count);
    return index;
}
 
/* Driver program to test above function */
int main()
{
    char str[] = "geeksforgeeks";
    int index = firstNonRepeating(str);
    if (index == -1)
        printf("Either all characters are repeating or "
               "string is empty");
    else
        printf("First non-repeating character is %c",
               str[index]);
    getchar();
    return 0;
}


Java




// Java program to find first
// non-repeating character
 
import java.io.*;
 
class GFG {
    static final int NO_OF_CHARS = 256;
    static char count[] = new char[NO_OF_CHARS];
 
    /* calculate count of characters
       in the passed string */
    static void getCharCountArray(String str)
    {
        for (int i = 0; i < str.length(); i++)
            count[str.charAt(i)]++;
    }
 
    /* The method returns index of first non-repeating
       character in a string. If all characters are
       repeating then returns -1 */
    static int firstNonRepeating(String str)
    {
        getCharCountArray(str);
        int index = -1, i;
 
        for (i = 0; i < str.length(); i++) {
            if (count[str.charAt(i)] == 1) {
                index = i;
                break;
            }
        }
 
        return index;
    }
 
    // Driver method
    public static void main(String[] args)
    {
        String str = "geeksforgeeks";
        int index = firstNonRepeating(str);
 
        System.out.println(
            index == -1
                ? "Either all characters are repeating or string "
                      + "is empty"
                : "First non-repeating character is "
                      + str.charAt(index));
    }
}


Python3




# Python program to print the first non-repeating character
NO_OF_CHARS = 256
 
# Returns an array of size 256 containing count
# of characters in the passed char array
 
 
def getCharCountArray(string):
    count = [0] * NO_OF_CHARS
    for i in string:
        count[ord(i)] += 1
    return count
 
# The function returns index of first non-repeating
# character in a string. If all characters are repeating
# then returns -1
 
 
def firstNonRepeating(string):
    count = getCharCountArray(string)
    index = -1
    k = 0
 
    for i in string:
        if count[ord(i)] == 1:
            index = k
            break
        k += 1
 
    return index
 
 
# Driver program to test above function
string = "geeksforgeeks"
index = firstNonRepeating(string)
if index == 1:
    print("Either all characters are repeating or string is empty")
else:
    print("First non-repeating character is", string[index])
 
# This code is contributed by Bhavya Jain


C#




// C# program to find first non-repeating character
using System;
using System.Globalization;
 
class GFG {
 
    static int NO_OF_CHARS = 256;
    static char[] count = new char[NO_OF_CHARS];
 
    /* calculate count of characters
    in the passed string */
    static void getCharCountArray(string str)
    {
        for (int i = 0; i < str.Length; i++)
            count[str[i]]++;
    }
 
    /* The method returns index of first non-repeating
    character in a string. If all characters are
    repeating then returns -1 */
    static int firstNonRepeating(string str)
    {
        getCharCountArray(str);
        int index = -1, i;
 
        for (i = 0; i < str.Length; i++) {
            if (count[str[i]] == 1) {
                index = i;
                break;
            }
        }
 
        return index;
    }
 
    // Driver code
    public static void Main()
    {
        string str = "geeksforgeeks";
        int index = firstNonRepeating(str);
 
        Console.WriteLine(
            index == -1
                ? "Either "
                      + "all characters are repeating or string "
                      + "is empty"
                : "First non-repeating character"
                      + " is " + str[index]);
    }
}
 
// This code is contributed by Sam007


Javascript




// javascript program to find first
// non-repeating character
 
 
/* Returns an array of size 256 containing count
of characters in the passed char array */
function getCharCountArray(str)
{
    let count = new Array(256).fill(0);
    let i;
    for (i = 0; i < str.length; i++)
        count[str[i].charCodeAt(0)]++;
     
    return count;
}
 
/* The function returns index of first
non-repeating character in a string. If all
characters are repeating then returns -1 */
function firstNonRepeating(str){
     
    let count = getCharCountArray(str);
    let index = -1
    let i;
 
     
    for (i = 0; i < str.length; i++) {
        if (count[str[i].charCodeAt(0)] == 1) {
            index = i;
            break;
        }
    }
 
    // To avoid memory leak
    return index;
}
 
/* Driver program to test above function */
let str = "geeksforgeeks";
let index = firstNonRepeating(str);
if (index == -1)
    console.log("Either all characters are repeating or string is empty");
else
    console.log("First non-repeating character is ", str[index]);
 
 
// This code is contributed by Nidhi goel.


PHP




<?php
// PHP program to find
// first non-repeating
// character
$NO_OF_CHARS = 256;
$count=array_fill(0, 200, 0);
 
/* calculate count
   of characters in 
   the passed string */
function getCharCountArray($str)
{
    global $count;
    for ($i = 0;
         $i < strlen($str); $i++)
        $count[ord($str[$i])]++;
}
 
/* The method returns index
of first non-repeating
character in a string. If
all characters are repeating
then returns -1 */
function firstNonRepeating($str)
{
    global $count;
    getCharCountArray($str);
    $index = -1;
    for ($i = 0;
         $i < strlen($str); $i++)
    {
        if ($count[ord($str[$i])] == 1)
        {
            $index = $i;
            break;
        }
    }
     
return $index;
}
 
// Driver code
$str = "geeksforgeeks";
$index = firstNonRepeating($str);
if($index == -1)
echo "Either all characters are" .
     " repeating or string is empty";
else
echo "First non-repeating ".
            "character is ".
               $str[$index];
 
// This code is contributed by mits
?>


Output

First non-repeating character is f

Time Complexity: O(N), Traversing over the string of size N
Auxiliary Space: O(256), To store the frequency of the characters in the string.

First non-repeating character using HashMap and single string traversal

The idea is to make a count array instead of a hash_map of a maximum number of characters(256). Augment the count array by storing not just counts but also the index of the first time a character is encountered. So when it comes to finding the first non-repeater, just have to scan the count array, instead of the string.

Follow the steps below to solve the problem:

  • Make a count_array which will have two fields namely frequency, first occurrence of a character.
  • The size of count_array is 256.
  • Traverse the given string using a pointer.
  • Increase the count of current characters and update the occurrence.
  • Now here’s a catch, the array will contain a valid first occurrence of the character which has frequency of unity. Otherwise, the first occurrence keeps updating.
  • Now traverse the count_array[] and find the character with the least first occurrence value and frequency value as unity.
  • Return that character.

Below is the implementation of the above approach.

C++




// CPP program to find first non-repeating
// character
#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)
{
    pair<int, int> arr[NO_OF_CHARS];
 
    for (int i = 0; str[i]; i++) {
        (arr[str[i]].first)++;
        arr[str[i]].second = i;
    }
 
    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].first == 1)
            res = min(res, arr[i].second);
 
    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;
}


C




#include <limits.h>
#include <stdio.h>
#include <stdlib.h>
#define NO_OF_CHARS 256
 
// Structure to store count of a
// character and index of the first
// occurrence in the input string
struct countIndex {
    int count;
    int index;
};
 
/* Returns an array of above
structure type. The size of
array is NO_OF_CHARS */
struct countIndex* getCharCountArray(char* str)
{
    struct countIndex* count = (struct countIndex*)calloc(
        sizeof(struct countIndex), NO_OF_CHARS);
    int i;
    for (i = 0; *(str + i); i++) {
        (count[*(str + i)].count)++;
 
        // If it's first occurrence,
        // then store the index
        if (count[*(str + i)].count == 1)
            count[*(str + i)].index = i;
    }
    return count;
}
 
/* 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)
{
    struct countIndex* count = getCharCountArray(str);
    int result = INT_MAX, i;
 
    for (i = 0; i < NO_OF_CHARS; i++) {
        // If this character occurs
        // only once and appears
        // before the current result,
        // then update the result
        if (count[i].count == 1 && result > count[i].index)
            result = count[i].index;
    }
 
    // To avoid memory leak
    free(count);
    return result;
}
 
/* 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]);
    getchar();
    return 0;
}


Java




// Java program to find first
// non-repeating character
// Note : hashmap is used
 
import java.util.*;
 
class CountIndex {
    int count, index;
 
    // constructor for first occurrence
    public CountIndex(int index)
    {
        this.count = 1;
        this.index = index;
    }
 
    // method for updating count
    public void incCount() { this.count++; }
}
class GFG {
    static final int NO_OF_CHARS = 256;
 
    static HashMap<Character, CountIndex> hm
        = new HashMap<Character, CountIndex>(NO_OF_CHARS);
 
    /* calculate count of characters
       in the passed string */
    static void getCharCountArray(String str)
    {
        for (int i = 0; i < str.length(); i++) {
            // If character already occurred,
            if (hm.containsKey(str.charAt(i))) {
                // updating count
                hm.get(str.charAt(i)).incCount();
            }
 
            // If it's first occurrence, then store
            // the index and count = 1
            else {
                hm.put(str.charAt(i), new CountIndex(i));
            }
        }
    }
 
    /* The method returns index of first non-repeating
       character in a string. If all characters are
       repeating then returns -1 */
    static int firstNonRepeating(String str)
    {
        getCharCountArray(str);
        int result = Integer.MAX_VALUE, i;
        for (Map.Entry<Character, CountIndex> entry :
             hm.entrySet()) {
            int c = entry.getValue().count;
            int ind = entry.getValue().index;
            if (c == 1 && ind < result) {
                result = ind;
            }
        }
 
        return result;
    }
 
    // Driver method
    public static void main(String[] args)
    {
        String str = "geeksforgeeks";
        int index = firstNonRepeating(str);
 
        System.out.println(
            index == Integer.MAX_VALUE
                ? "Either all characters are repeating "
                      + " or string is empty"
                : "First non-repeating character is "
                      + str.charAt(index));
    }
}


Python3




# Python3 program to find first non-repeating
# character
import sys
 
NO_OF_CHARS = 256
 
#    The function returns index of the first
#    non-repeating character in a string. If
#    all characters are repeating then
#    returns sys.maxsize :
 
 
def firstNonRepeating(Str):
 
    arr = [[] for i in range(NO_OF_CHARS)]
    for i in range(NO_OF_CHARS):
        arr[i] = [0, 0]
 
    for i in range(len(Str)):
        arr[ord(Str[i])][0] += 1
        arr[ord(Str[i])][1] = i
 
    res = sys.maxsize
    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] == 1):
            res = min(res, arr[i][1])
 
    return res
 
 
# Driver program to test above functionS
Str = "geeksforgeeks"
index = firstNonRepeating(Str)
if (index == sys.maxsize):
    print("Either all characters are repeating or string is empty")
else:
    print("First non-repeating character is ", Str[index])
 
# This code is contributed by shinjanpatra


C#




// C# program to find first
// non-repeating character
// Note : hashmap is used
using System;
using System.Collections.Generic;
 
class CountIndex {
    public int count, index;
 
    // constructor for first occurrence
    public CountIndex(int index)
    {
        this.count = 1;
        this.index = index;
    }
 
    // method for updating count
    public virtual void incCount() { this.count++; }
}
 
class GFG {
    public const int NO_OF_CHARS = 256;
 
    public static Dictionary<char, CountIndex> hm
        = new Dictionary<char, CountIndex>(NO_OF_CHARS);
 
    /* calculate count of characters
    in the passed string */
    public static void getCharCountArray(string str)
    {
        for (int i = 0; i < str.Length; i++) {
            // If character already occurred,
            if (hm.ContainsKey(str[i])) {
                // updating count
                hm[str[i]].incCount();
            }
 
            // If it's first occurrence, then
            // store the index and count = 1
            else {
                hm[str[i]] = new CountIndex(i);
            }
        }
    }
 
    /* The method returns index of first
    non-repeating character in a string.
    If all characters are repeating then
    returns -1 */
    internal static int firstNonRepeating(string str)
    {
        getCharCountArray(str);
        int result = int.MaxValue, i;
 
        for (i = 0; i < str.Length; i++) {
            // If this character occurs only
            // once and appears before the
            // current result, then update the result
            if (hm[str[i]].count == 1
                && result > hm[str[i]].index) {
                result = hm[str[i]].index;
            }
        }
 
        return result;
    }
 
    // Driver Code
    public static void Main(string[] args)
    {
        string str = "geeksforgeeks";
        int index = firstNonRepeating(str);
 
        Console.WriteLine(
            index == int.MaxValue
                ? "Either all characters are repeating "
                      + " or string is empty"
                : "First non-repeating character is "
                      + str[index]);
    }
}
 
// This code is contributed by Shrikant13


Javascript




<script>
 
// JavaScript program to find first non-repeating
// character
 
const NO_OF_CHARS = 256
 
/* The function returns index of the first
   non-repeating character in a string. If
   all characters are repeating then
   returns Number.MAX_VALUE */
function firstNonRepeating(str)
{
    let arr = new Array(NO_OF_CHARS)
    for(let i=0;i<NO_OF_CHARS;i++){
        arr[i] = [0,0];
    }
 
    for (let i=0;i<str.length;i++) {
        arr[str.charCodeAt(i)][0]++;
        arr[str.charCodeAt(i)][1]= i;
    }
 
    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] == 1)
            res = Math.min(res, arr[i][1]);
 
    return res;
}
 
/* Driver program to test above function */
 
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]);
     
// code is contributed by shinjanpatra
 
</script>


Output

First non-repeating character is f

Time Complexity: O(N), As the string needs to be traversed at least once.
Auxiliary Space: O(256), Space is occupied by the use of count_array/hash_map to keep track of frequency.

First non-repeating character using Count array and single string traversal:

The idea is to mark the repeated elements with some value let’s say -2 and the one who repeated one time will be marked with the current index.

Follow the steps below to solve the problem:

  • Make a count array of a maximum number of characters(256) and initialize all the elements in this array to -1
  • Then loop through the string character by character and check if the array element with this character as the index is -1 or not. 
  • If it is -1 then change it to i and. If it is not -1, then this means that this character already appeared before, so change it to -2
  • In the end, all the repeating characters will be changed to -2 and all non-repeating characters will contain the index where they occur. 
  • Now, just loop through all the non-repeating characters and find the minimum index or the first index.

Below is the implementation of the above approach.

C++




// CPP program to find first non-repeating
// character
#include <climits>
#include <iostream>
 
using namespace std;
 
// this function return the index of first non-repeating
// character if found, or else it returns -1
int firstNonRepeating(string str)
{
    int fi[256]; // array to store First Index
 
    // initializing all elements to -1
    for (int i = 0; i < 256; i++)
        fi[i] = -1;
 
    // sets all repeating characters to -2 and non-repeating
    // characters contain the index where they occur
    for (int i = 0; i < str.length(); i++) {
        if (fi[str[i]] == -1) {
            fi[str[i]] = i;
        }
        else {
            fi[str[i]] = -2;
        }
    }
 
    int res = INT_MAX;
 
    for (int i = 0; i < 256; i++) {
 
        // If this character is not -1 or -2 then it
        // means that this character occurred only once
        // so find the min index of all characters that
        // occur only once, that's our first index
        if (fi[i] >= 0)
            res = min(res, fi[i]);
    }
 
    // if res remains INT_MAX, it means there are no
    // characters that repeat only once or the string is
    // empty
    if (res == INT_MAX)
        return -1;
    else
        return res;
}
 
int main()
{
    string str;
    str = "geeksforgeeks";
    int firstIndex = firstNonRepeating(str);
    if (firstIndex == -1)
        cout << "Either all characters are repeating or "
                "string is empty";
    else
        cout << "First non-repeating character is "
             << str[firstIndex];
 
    return 0;
}


Java




// JAVA program to find first non-repeating
// character
public class GFG {
 
    // this function return the index of first non-repeating
    // character if found, or else it returns -1
    public static int firstNonRepeating(String str)
    {
        int[] fi
            = new int[256]; // array to store First Index
 
        // initializing all elements to -1
        for (int i = 0; i < 256; i++)
            fi[i] = -1;
 
        // sets all repeating characters to -2 and
        // non-repeating characters contain the index where
        // they occur
        for (int i = 0; i < str.length(); i++) {
            if (fi[str.charAt(i)] == -1) {
                fi[str.charAt(i)] = i;
            }
            else {
                fi[str.charAt(i)] = -2;
            }
        }
 
        int res = Integer.MAX_VALUE;
 
        for (int i = 0; i < 256; i++) {
 
            // If this character is not -1 or -2 then it
            // means that this character occurred only once
            // so find the min index of all characters that
            // occur only once, that's our first index
            if (fi[i] >= 0)
                res = Math.min(res, fi[i]);
        }
 
        // if res remains  Integer.MAX_VALUE, it means there
        // are no characters that repeat only once or the
        // string is empty
        if (res == Integer.MAX_VALUE)
            return -1;
        else
            return res;
    }
 
    public static void main(String args[])
    {
        String str;
        str = "geeksforgeeks";
        int firstIndex = firstNonRepeating(str);
        if (firstIndex == -1)
            System.out.println(
                "Either all characters are repeating or string is empty");
        else
            System.out.println(
                "First non-repeating character is "
                + str.charAt(firstIndex));
    }
}
// This code is contributed by SoumikMondal


Python3




# this function return the index of first non-repeating
# character if found, or else it returns -1
import sys
 
 
def firstNonRepeating(Str):
    fi = [-1 for i in range(256)]
 
    # sets all repeating characters to -2 and non-repeating characters
    # contain the index where they occur
    for i in range(len(Str)):
 
        if(fi[ord(Str[i])] == -1):
            fi[ord(Str[i])] = i
        else:
            fi[ord(Str[i])] = -2
 
    res = sys.maxsize
 
    for i in range(256):
 
        # If this character is not -1 or -2 then it
        # means that this character occurred only once
        # so find the min index of all characters that
        # occur only once, that's our first index
        if(fi[i] >= 0):
            res = min(res, fi[i])
 
    # if res remains INT_MAX, it means there are no
    # characters that repeat only once or the string is empty
    if(res == sys.maxsize):
        return -1
    else:
        return res
 
 
Str = "geeksforgeeks"
firstIndex = firstNonRepeating(Str)
 
if (firstIndex == -1):
    print("Either all characters are repeating or string is empty")
else:
    print("First non-repeating character is " + str(Str[firstIndex]))
 
# This code is contributed by shinjanpatra


C#




// C# program to find first non-repeating
// character
using System;
public class GFG {
 
    // this function return the index of first non-repeating
    // character if found, or else it returns -1
    public static int firstNonRepeating(string str)
    {
        int[] fi
            = new int[256]; // array to store First Index
 
        // initializing all elements to -1
        for (int i = 0; i < 256; i++)
            fi[i] = -1;
 
        // sets all repeating characters to -2 and
        // non-repeating characters contain the index where
        // they occur
        for (int i = 0; i < str.Length; i++) {
            if (fi[str[i]] == -1) {
                fi[str[i]] = i;
            }
            else {
                fi[str[i]] = -2;
            }
        }
 
        int res = Int32.MaxValue;
 
        for (int i = 0; i < 256; i++) {
 
            // If this character is not -1 or -2 then it
            // means that this character occurred only once
            // so find the min index of all characters that
            // occur only once, that's our first index
            if (fi[i] >= 0)
                res = Math.Min(res, fi[i]);
        }
 
        // if res remains  Integer.MAX_VALUE, it means there
        // are no characters that repeat only once or the
        // string is empty
        if (res == Int32.MaxValue)
            return -1;
        else
            return res;
    }
 
    public static void Main()
    {
        string str;
        str = "geeksforgeeks";
        int firstIndex = firstNonRepeating(str);
        if (firstIndex == -1)
            Console.WriteLine(
                "Either all characters are repeating or string is empty");
        else
            Console.WriteLine(
                "First non-repeating character is "
                + str[firstIndex]);
    }
}
 
// This code is contributed by ukasp.


Javascript




<script>
 
// this function return the index of first non-repeating
// character if found, or else it returns -1
function firstNonRepeating(str)
{
    var fi=new Array(256);
     
    // array to store First Index
    fi.fill(-1);
 
    // initializing all elements to -1
    for(var i = 0; i<256; i++)
        fi[i] = -1;
 
    // sets all repeating characters to -2 and non-repeating characters
    // contain the index where they occur
    for(var i = 0; i<str.length; i++)
    {
        if(fi[str.charCodeAt(i)] ==-1)
        {
            fi[str.charCodeAt(i)] = i;
             
        }
        else
        {
            fi[str.charCodeAt(i)] = -2;
        }
    }
 
    var res = Infinity;
 
    for(var i = 0; i<256; i++) {
 
        // If this character is not -1 or -2 then it
        // means that this character occurred only once
        // so find the min index of all characters that
        // occur only once, that's our first index
        if(fi[i] >= 0)
            res = Math.min(res, fi[i]);
    }
     
    // if res remains INT_MAX, it means there are no
    // characters that repeat only once or the string is empty
    if(res == Infinity) return -1;
    else return res;
}
 
var str;
    str = "geeksforgeeks";
    var firstIndex = firstNonRepeating(str);
    if (firstIndex === -1)
        document.write("Either all characters are repeating or string is empty");
    else
        document.write("First non-repeating character is "+ str.charAt(firstIndex));
     
// This code is contributed by akshitsaxenaa09.   
</script>


Output

First non-repeating character is f

Time Complexity: O(N), As the string needs to be traversed once
Auxiliary Space: O(1), Space is occupied by the use of count-array to keep track of frequency.

First non-repeating character using Built-in Python Functions:

The idea is to find the frequency of all characters in the string and check which character has a unit frequency.

Follow the steps below to solve the problem:

  • Calculate all frequencies of all characters using Counter() function.
  • Traverse the string and check if any element has frequency 1.
  • Print the character and break the loop.

Below is the implementation of the above approach:

C++




#include <iostream>
#include <string>
#include <unordered_map>
 
using namespace std;
 
// Function which repeats first non-repeating character
void printNonrepeated(string str) {
    // Calculating frequencies using unordered_map
    unordered_map<char, int> freq;
    for(char c : str) {
        freq++;
    }
 
    // Traverse the string
    for(char c : str) {
        if(freq == 1) {
            cout << "First non-repeating character is " << c << endl;
            return;
        }
    }
}
 
// Driver code
int main() {
    string str = "geeksforgeeks";
    // Passing string to printNonrepeated function
    printNonrepeated(str);
    return 0;
}


Java




import java.util.HashMap;
import java.util.Map;
 
class Main {
    public static void main(String[] args)
    {
        String str = "geeksforgeeks";
        printNonrepeated(str);
    }
 
    // Function which repeats first non-repeating character
    static void printNonrepeated(String str)
    {
        // Calculating frequencies using HashMap
        Map<Character, Integer> freq
            = new HashMap<Character, Integer>();
        for (char c : str.toCharArray()) {
            freq.put(c, freq.getOrDefault(c, 0) + 1);
        }
 
        // Traverse the string
        for (char c : str.toCharArray()) {
            if (freq.get(c) == 1) {
                System.out.println(
                    "First non-repeating character is "
                    + c);
                return;
            }
        }
    }
}
 
// This code is contributed by Susobhan Akhuli


Python3




# Python implementation
from collections import Counter
 
# Function which repeats
# first Nonrepeating character
 
 
def printNonrepeated(string):
 
    # Calculating frequencies
    # using Counter function
    freq = Counter(string)
 
    # Traverse the string
    for i in string:
        if(freq[i] == 1):
            print("First non-repeating character is " + i)
            break
 
 
# Driver code
string = "geeksforgeeks"
 
# passing string to printNonrepeated function
printNonrepeated(string)
 
# this code is contributed by vikkycirus


C#




// C# implementation
using System;
using System.Collections.Generic;
using System.Linq;
 
// Function which repeats
// first Nonrepeating character
class Program
{
static void PrintNonrepeated(string str)
{
      // Calculating frequencies
    // using LINQ
    Dictionary<char, int> freq = str.GroupBy(c => c).ToDictionary(g => g.Key, g => g.Count());
 
    // Traverse the string
    foreach (char c in str)
    {
        if (freq == 1)
        {
            Console.WriteLine("First non-repeating character is " + c);
            break;
        }
    }
}
 
// Driver code
static void Main(string[] args)
{
    string str = "geeksforgeeks";
 
    // passing string to printNonrepeated function
    PrintNonrepeated(str);
}
}
// this code is contributed by shivamshivam215


Javascript




// Javascript ptogram for the above approach
 
// Function which repeats first non-repeating character
function printNonrepeated(string) {
  // Calculating frequencies using object
  let freq = {};
  for (let i = 0; i < string.length; i++) {
    freq[string[i]] = (freq[string[i]] || 0) + 1;
  }
 
  // Traverse the string
  for (let i = 0; i < string.length; i++) {
    if (freq[string[i]] === 1) {
      console.log("First non-repeating character is " + string[i]);
      break;
    }
  }
}
 
// Driver code
let string = "geeksforgeeks";
 
// passing string to printNonrepeated function
printNonrepeated(string);
 
// This code is contributed by codebraxnzt


Output

First non-repeating character is f


Time Complexity: O(N). As the string needs to be traversed at least once.
Auxiliary Space: O(256), Space is occupied by the use of the frequency array.

Approach: Sorting and Counting

One possible approach to solving this problem is to use a sorting function to rearrange the string characters in ascending order, which can make it easier to identify repeating characters. Then, we can iterate through the sorted string and check for each character if it appears only once in the string. The first such character we encounter will be the first non-repeating character.

Here are the steps for this approach:

  1. Convert the string to a list of characters to make it mutable.
  2. Sort the list of characters in ascending order.
  3. Initialize a dictionary to keep track of the count of each character in the string.
  4. Iterate through the sorted list of characters and update the count of each character in the dictionary.
  5. Iterate through the sorted list of characters again and check for each character if its count in the dictionary is 1. If so,
  6. return that character as the first non-repeating character.
  7. If no non-repeating character is found, return None.

C++




#include <iostream>
#include <algorithm>
#include <unordered_map>
 
char find_first_non_repeating_char(std::string s) {
    std::sort(s.begin(), s.end());
    std::unordered_map<char, int> count;
    for (char c : s) {
        if (count.count(c)) {
            count += 1;
        } else {
            count = 1;
        }
    }
    for (char c : s) {
        if (count == 1) {
            return c;
        }
    }
    return '\0';
}
 
int main() {
    std::cout << find_first_non_repeating_char("geeksforgeeks") << std::endl;
    return 0;
}


Java




import java.util.Arrays;
import java.util.HashMap;
import java.util.Map;
 
public class Main {
    public static Character findFirstNonRepeatingChar(String s) {
        char[] chars = s.toCharArray();
        Arrays.sort(chars);
        Map<Character, Integer> count = new HashMap<>();
        for (char c : chars) {
            count.put(c, count.getOrDefault(c, 0) + 1);
        }
        for (char c : chars) {
            if (count.get(c) == 1) {
                return c;
            }
        }
        return null;
    }
 
    public static void main(String[] args) {
        System.out.println(findFirstNonRepeatingChar("geeksforgeeks")); // Output: 'f'
    }
}


Python3




def find_first_non_repeating_char(s):
    chars = list(s)
    chars.sort()
    count = {}
    for c in chars:
        if c in count:
            count += 1
        else:
            count = 1
    for c in chars:
        if count == 1:
            return c
    return None
 
print(find_first_non_repeating_char("geeksforgeeks"))
 
#This article is contributed by Dhanalaxmi


C#




using System;
using System.Collections.Generic;
 
public class Program {
    public static char FindFirstNonRepeatingChar(string s)
    {
        List<char> chars = new List<char>(s);
        chars.Sort();
        Dictionary<char, int> count
            = new Dictionary<char, int>();
 
        foreach(char c in chars)
        {
            if (count.ContainsKey(c)) {
                count += 1;
            }
            else {
                count = 1;
            }
        }
 
        foreach(char c in chars)
        {
            if (count == 1) {
                return c;
            }
        }
 
        return '\0'; // Returns null character if no
                     // non-repeating character found
    }
 
    public static void Main(string[] args)
    {
        Console.WriteLine(
            FindFirstNonRepeatingChar("geeksforgeeks"));
    }
}


Javascript




function find_first_non_repeating_char(s) {
    let chars = s.split('');
    chars.sort();
    let count = {};
    for (let c of chars) {
        if (c in count) {
            count += 1;
        } else {
            count = 1;
        }
    }
    for (let c of chars) {
        if (count == 1) {
            return c;
        }
    }
    return null;
}
 
console.log(find_first_non_repeating_char("geeksforgeeks"));


Output

f


The time complexity of this approach is O(n log n), where n is the length of the string, due to the sorting step. 

The auxiliary space complexity is O(n)

Approach : One Liner Java 8 Solution

The similar problem can be solved in Java 8 stream API using one-liner solution as follows –

Java




/*package whatever //do not write package name here */
 
import java.io.*;
import java.util.LinkedHashMap;
import java.util.function.Function;
import java.util.stream.Collectors;
 
class GFG {
   
    private static char findFirstNonRepeatingCharacter(String s) {
        return s.chars()
                .mapToObj(x -> Character.toLowerCase((char) x))
                .collect(Collectors.groupingBy(Function.identity(),
                                               LinkedHashMap::new, Collectors.counting()))
                .entrySet()
                .stream()
                .filter(x -> x.getValue() == 1)
                .findFirst()
                .orElseThrow()
                .getKey();
    }
   
    public static void main (String[] args) {
        System.out.println(findFirstNonRepeatingCharacter("geeksforgeeks"));
    }
}


Time Complexity : O(n)

Space Complexity : O(n) //As internally it is using a new Map to store data

Related Problem: K’th Non-repeating Character



Last Updated : 15 Oct, 2023
Like Article
Save Article
Previous
Next
Share your thoughts in the comments
Similar Reads