Find First Non-Repeating Character – Python

The task is to identify the first non-repeating character in a given string. For instance, in the string “swiss”, the first character that does not repeat is ‘w’.

def first_non_repeating(s):
    from collections import Counter
    count = Counter(s)
    return next((char for char in s if count[char] == 1), None)

# Example usage
result = first_non_repeating("swiss")
print(result)  # Output: 'w'

In the above example, we are using the collections.Counter class to count character occurrences.

  1. Importing Counter: The function begins by importing the Counter class from the collections module.
  2. Counting Characters: It then creates a Counter object that counts the occurrences of each character in the input string s.
  3. Finding the First Non-Repeating Character: Using a generator expression, the function iterates through the string and returns the first character with a count of 1. If no such character exists, it returns None.