Skip to Content

First Unique Character in a String

Home | Coding Interviews | Arrays and Strings | First Unique Character in a String

Given a string s, find the first non-repeating character in it and return its index. If it does not exist, return -1

class Solution(object):
    def firstUniqChar(self, s):
        hset = collections.Counter(s);
        # Traverse the string from the beginning...
        for idx in range(len(s)):
            # If the count is equal to 1, it is the first distinct character in the list.
            if hset[s[idx]] == 1:
                return idx
        return -1       # If no character appeared exactly once...

Posted by Jamie Meyer 22 days ago