Non-repeating character in a string

This problem is about finding the first non-repeating character in a 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'.
Input:
"GeeksforGeeks"
Output:
'f'

Solution

This solution is in Python. Our A.I. can create solutions in multiple languages.
by kayakane
# Solution:
# The solution below is optimal because it uses a dictionary to store the characters and their counts.
# The dictionary is then iterated over to find the first character with a count of 1.
# The time complexity of this solution is O(n) because the dictionary is iterated over once.
# The space complexity of this solution is O(n) because the dictionary is the same size as the input string.

def first_non_repeating_character(string):
    char_counts = {}
    for char in string:
        if char in char_counts:
            char_counts[char] += 1
        else:
            char_counts[char] = 1
    for char in string:
        if char_counts[char] == 1:
            return char
    return None

print(first_non_repeating_character("GeeksforGeeks"))

A.I. Evaluation of the Solution

The candidate's solution is correct and uses a dictionary to store the characters and their counts. The time complexity of this solution is O(n) because the dictionary is iterated over once. The space complexity of this solution is O(n) because the dictionary is the same size as the input string.

Evaluated at: 2022-12-01 00:15:41