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 store index if 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;` `}` |

*chevron_right*

*filter_none*

## 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));` `}` `}` |

*chevron_right*

*filter_none*

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

*chevron_right*

*filter_none*

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

*chevron_right*

*filter_none*

**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)` |

*chevron_right*

*filter_none*

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

## Recommended Posts:

- Efficiently find first repeated character in a string without using any additional data structure in one traversal
- Check if frequency of character in one string is a factor or multiple of frequency of same character in other string
- Map every character of one string to another such that all occurrences are mapped to the same character
- Count of substrings having the most frequent character in the string as first character
- Lexicographically smallest string formed by appending a character from first K characters of a string | Set 2
- Sub-strings that start and end with one character and have at least one other
- Lengths of maximized partitions of a string such that each character of the string appears in one substring
- Maximized partitions of a string such that each character of the string appears in one substring
- Convert the string into palindrome string by changing only one character
- Lexicographically smallest string formed by appending a character from the first K characters of a given string
- Queries to find the first non-repeating character in the sub-string of a string
- Find the character in first string that is present at minimum index in second string
- Find first non-repeating character in a given string using Linked List
- Find a string such that every character is lexicographically greater than its immediate next character
- Replace every character of string by character whose ASCII value is K times more than it
- Replace every character of a string by a different character
- Modify the string such that every character gets replaced with the next character in the keyboard
- Replace all occurrences of character X with character Y in given string
- Longest Common Prefix using Character by Character Matching
- Check if both halves of the string have at least one different character

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.