How To Find first non-repeating character in a string by doing only one traversal of it?

Given a string, find first non-repeating character in it by doing only one traversal of it.

For example,

Input:
string is ABCDBAGHC
Output:
The first non-repeating character in the string is D

A simple solution would be to store count of each character in a map or an array by traversing it once. Then we traverse the string once more to find the first character having its count as 1. The time complexity of this solution is O(n) and auxiliary space used is O(n). The problem in this solution is that we are traversing the string twice and it violates the program constraints.

We can solve this problem in single traversal of the string. The idea is to use a map to store each distinct character count and the index of its first or last occurrence in the string. Finally, we traverse the map and find character having count 1 and minimum index in the string. Note that in this solution we are doing one traversal of the string and one traversal of the map. Since, the size of the map is equal to alphabet size in worst-case (which is a constant), it can be ignored.

C++ implementation –

Output:

The first non-repeating character in the string is D

The time complexity of this solution is O(n) and auxiliary space used by the program is O(1).