First non-repeating character in a string

This problem deals with finding the first non-repeating character in a given string. For example, if the input string is "GeeksforGeeks", then the output should be ' f'.

Problem

Given a string, find the first non-repeating character in it. For example, if the input string is "GeeksforGeeks", then the output should be 'f' and if the input string is "GeeksQuiz", then the output should be 'G'.
Input:
"GeeksforGeeks"
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 (char c : s) {
        charCount[c]++;
    }
    for (char c : s) {
        if (charCount[c] == 1) {
            return c;
        }
    }
    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. This would allow the characters to be iterated over in the order in which they appear in the string, which would make the second loop unnecessary.

Evaluated at: 2022-12-03 14:15:41