Find the First Non-Repeating Character in a String

Given a string, this function finds the first non-repeating character in it.

Problem

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 the input string is "GeeksQuiz", then output should be 'G'.
Example input: "GeeksforGeeks"
Example output: 'f'

Solution

This solution is in C++. Our A.I. can create solutions in multiple languages.
by kayakane
#include <iostream>
#include <string>
#include <unordered_map>

using namespace std;

char firstNonRepeatingChar(string s) {
    unordered_map<char, int> charCount;
    for (int i = 0; i < s.length(); i++) {
        charCount[s[i]]++;
    }
    for (int i = 0; i < s.length(); i++) {
        if (charCount[s[i]] == 1) {
            return s[i];
        }
    }
    return '\0';
}

int main() {
    string s = "GeeksforGeeks";
    cout << firstNonRepeatingChar(s) << endl;
    return 0;
}

A.I. Evaluation of the Solution

The candidate's solution correctly finds the first non-repeating character in a string. The solution uses a hash map to keep track of the number of times each character appears in the string, then loops through the string again to find the first character with a count of 1. One potential improvement to this solution would be to use a LinkedHashMap instead of a regular hash map, so that the order in which the characters are added to the map is preserved. This would allow the solution to find the first non-repeating character in the string in a single loop, without having to loop through the string twice.

Evaluated at: 2022-12-10 12:15:23